/**
     * Helper for solr raw searches.
     * Deals with the language, meta_installation, section and visibility filters + solr sharding if any
     * @param array $params
     * @param string $requestType
     * @param bool $useDefaultFilters
     * @return array
     */
    public static function rawSearch( $params, $requestType = 'php', $useDefaultFilters = true, $includeIsInvisible = true )
    {
        eZDebug::accumulatorStart( __CLASS__ . '::' . __FUNCTION__, 'Merck' );

        $findINI = eZINI::instance( 'ezfind.ini' );
        $solrINI = eZINI::instance( 'solr.ini' );
        $siteINI = eZINI::instance();
        $currentLanguage = $siteINI->variable( 'RegionalSettings', 'ContentObjectLocale' );

        // always use extended Dismax query handler when available
        if( isset($params['qt']) && $params['qt'] == 'ezpublish' )
            $params['defType'] = 'edismax';

        if ( $useDefaultFilters )
        {
            if ( !isset( $params['fq'] ) )
                $params['fq'] = '';
            else
                $params['fq'] .= ' AND ';
            $params['fq'] .= implode( ' AND ', array(
                'meta_installation_id_ms:' . eZSolr::installationID(),
                '(attr_offline_date_dt:"1970-01-01T01:00:00Z" OR attr_offline_date_dt:[NOW TO *])',
                '( meta_section_id_si:1 OR meta_section_id_si:3 )',
            ) );
            if ($includeIsInvisible) {
                $params['fq'] .= ' AND ' . 'attr_is_invisible_' . ClusterTool::clusterIdentifier() . '_b:false';
            }
        }

        if ( $findINI->variable( 'LanguageSearch', 'MultiCore' ) == 'enabled' )
        {
            $languageMapping = $findINI->variable( 'LanguageSearch', 'LanguagesCoresMap' );
            $shardMapping = $solrINI->variable( 'SolrBase', 'Shards' );
            $fullSolrURI = $shardMapping[$languageMapping[$currentLanguage]];
        }
        else
        {
            $fullSolrURI = $solrINI->variable( 'SolrBase', 'SearchServerURI' );
            // Autocomplete search should be done in current language and fallback languages
            $validLanguages = array_unique(
                array_merge(
                    LocaleTool::languageList(),
                    array( $currentLanguage )
                )
            );
            if( $useDefaultFilters )
                $params['fq'] .= ' AND meta_language_code_ms:(' . implode( ' OR ', $validLanguages ) . ')';
        }

        solrTool::solrStopWordsFilter( $params );    //excluding stopwords
        self::parseBooleanOperators( $params );      // translations for bookean operators
        $solrBase = new eZSolrBase( $fullSolrURI );
        $result = $solrBase->rawSolrRequest( '/select', $params, $requestType );
        if ( !$result )
            self::addNoCacheHeaders();
        
        eZDebug::accumulatorStop( __CLASS__ . '::' . __FUNCTION__ );

        return $result;
    }
    /**
     * @return bool
     */
    public function htmlBuildResult()
    {
        $this->pushResult('app'             , $this->applicationObject());
        $this->pushResult('view_parameters' , $this->_params['UserParameters']);

        if( $this->applicationObject()->attribute( 'identifier') == '2d-anatomy' )
        {
            $customParameters = $this->applicationObject()->getCustomParameter( 'LanguageSelectorValues' );
            if( $customParameters != false )
            {
                $this->pushResult( 'languagesSelector', $customParameters );
            }
            $this->pushResult( 'currentLanguage', LocaleTool::languageISO639Code() );
        }
        
        if( $this->applicationObject()->attribute( 'identifier') == 'login' )
        {
            header('Pragma: no-cache');
            header('cache-Control: no-cache, must-revalidate');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
        }
        return true;
    }
    /**
     * @param int $uxType
     * @param string $key
     * @param string $field
     */
    public function __construct($uxType, $key, $field)
    {
        parent::__construct($uxType, $key, $field);

        $this->canBeHidden     = true;
        $this->hideEmptyValues = false;

        if ( self::isForcedLanguage() )
        {
            $this->forcedValues = array( LocaleTool::languageISO639Code(LocaleTool::mainLanguage()) );
        }

        $defaultValues = array( LocaleTool::languageISO639Code() );
        foreach( LocaleTool::languageList() as $locale )
        {
            $language = LocaleTool::languageISO639Code( $locale );
            if( !isset($defaultValues[$language]) )
                $defaultValues[] = $language;
        }

        $this->defaultValues = $defaultValues;

        $overrideLanguageFacetIsActive = SolrSafeOperatorHelper::featureIsActive('DefaultLanguageFacetValues');
        if ($overrideLanguageFacetIsActive)
        {
            $forcedLanguageOverrides = SolrSafeOperatorHelper::feature('DefaultLanguageFacetValues', 'ApplicationDefaultLanguage');
            if (!empty($forcedLanguageOverrides))
            {
                $identifier = self::$applicationIdentifier;

                if (!empty($identifier) && isset($forcedLanguageOverrides[$identifier]))
                {
                    $this->forcedValues = $forcedLanguageOverrides[$identifier];
                }
            }
        }
    }
    /**
     * @param array|string $applications
     * @param int $offset
     * @param string|bool $template
     * @param bool $ordered
     * @return array
     */
    protected function fetchUserSelection( $applications = null, $offset = null, $template = false, $ordered = false )
    {
        header("Cache-Control: no-cache, must-revalidate");

        if( is_null( $applications ) && isset( $_POST['applications'] ) && $_POST['applications'] != 'null' )
        {
            $applications =  $_POST['applications'];
        }

        //TODO white liste to templates ?
        if( isset( $_POST['template'] ) )
        {
            $template = $_POST['template'];
        }

        if( isset( $_POST['ordered'] ) )
        {
            $ordered = $_POST['ordered'];
        }

        $elearningStatuses = isset( $_POST['st'] ) ? $_POST['st'] : null;

        if( !is_null($elearningStatuses) )
        {
            if( !is_array($applications) )
                $applications = array( 'e-learning' );
            else
                $applications[] = 'e-learning';
        }

        if(in_array("-1", $applications))
            $applications = null;

        if( is_null( $offset ) )
            $offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;

        $managedResults = $this->manageResults( MMSelections::fetchUserSelectionByApps( null, null, $applications, $elearningStatuses, $ordered ), $offset );
        $articles       = array();
        $fields         = array(
            'headline'          => 'attr_headline_s',
            'object_id'         => 'meta_id_si',
            'language'          => 'meta_language_code_ms',
            'has_image'         => 'attr_has_image_'.ClusterTool::clusterIdentifier().'_bst',
            'url'               => 'attr_' .  ClusterTool::clusterIdentifier() . '_url_s',
            'publisher_path'    => 'subattr_publisher_folder___source_id____s',
            'app_identifiers'   => 'subattr_parent_application___identifier____s'
        );

        /** @var String[][] $applicationUrls */
        $applicationsUrl = array();

        /** @var MMSelections $item */
        foreach($managedResults["items"] as $item)
        {
            $remote  = $item->attribute("remote_id");
            $locale  = LocaleTool::mainLanguage();
            $cluster = $item->attribute("cluster_identifier");

            $article = array(
                "description"        => $item->attribute("description"),
                "remote_id"          => $remote,
                "cluster_identifier" => $cluster,
                "application"        => $item->attribute("application"),
                "add_date"           => $item->attribute("add_date"),
                "is_visible"         => $item->attribute('is_visible'),
            );

            $fqPrimaryLanguage = implode(" AND ", array(
                "meta_remote_id_ms:".$remote,
                "meta_language_code_ms:".$locale
            ));

            $fqSecondaryLanguages = implode(" AND ", array(
                "meta_remote_id_ms:".$remote,
                "-meta_language_code_ms:".$locale,
                "-meta_available_language_codes_ms:".$locale,
            ));

            $params = array(
                'indent'        => 'on',
                'q'             => '',
                'start'         => 0,
                'rows'          => 1,
                'fq'            => "(($fqPrimaryLanguage) OR ($fqSecondaryLanguages))",
                'fl'            => implode(',', array_values($fields)),
                'qt'            => 'ezpublish',
                'explainOther'  => '',
                'hl.fl'         => '',
            );
            $raw = SolrTool::rawSearch($params);

            if(isset($raw["response"]["docs"][0]))
            {
                $rawArticle = $raw["response"]["docs"][0];

                $applicationIdentifier  = $item->attribute("application");
                $publisherPath          = $rawArticle[$fields["publisher_path"]][0];
                $publisherInfo          = PublisherFolderTool::getPathToIDMapping($publisherPath);
                $publisherFolderId      = $publisherInfo['pfid'];

                if( !in_array($applicationIdentifier, $applicationsUrl))
                {
                    $application = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );
                    
                    if ( $application instanceof ApplicationLocalized )
                    {
                        $applicationObject = $application->applicationObject();

                        $applicationsUrl[$applicationIdentifier]["url"] = $application->attribute('url_alias');
                        $applicationsUrl[$applicationIdentifier]["type"] = $applicationObject->applicationType()->attribute('type_identifier');
                    }
                    else
                    {
                        continue;
                    }
                }

                // since publisher refactor, we don't use the url in mm_selection_remote anymore, we use the url from solr instead
                $url = $rawArticle[$fields["url"]];

                switch ( $applicationsUrl[$applicationIdentifier]["type"] ) {
                    case 'evrika-calendar':
                    case 'clinical-trials':
                        $url = $applicationsUrl[$applicationIdentifier]["url"] . '/' . $url;
                        break;
                    case 'first-child':
                        $url = $applicationsUrl[$applicationIdentifier]["url"];
                        break;
                    default:
                        $url = $applicationsUrl[$applicationIdentifier]["url"] . '/' . $publisherFolderId . '/' . $url;
                }
                $additionnalFields = array(
                    "name"      => $rawArticle[$fields["headline"]],
                    "url"       => $url,
                    "object_id" => $rawArticle[$fields["object_id"]],
                    "language"  => $rawArticle[$fields["language"]],
                    "has_image" => json_decode( base64_decode($rawArticle[$fields["has_image"]]) ),
                );

                $article = array_merge($additionnalFields, $article);
            }

            $articles[] = $article;
        }

        $tpl = $this->tpl();
        $tpl->setVariable( 'my_selection_list', array( 'items' => $articles ) );
        $tpl->setVariable( 'facets', $managedResults['facets'] );

        if(!$template)
        {
            return array(
                'content' => array(
                    'articles'    => $tpl->fetch( 'design:esibuild/app_content/my-selection/line.tpl' ),
                    'articles_nb' => count($articles),
                    'num_found'   => $managedResults['total'],
                    'f'           => $tpl->fetch( 'design:esibuild/app_content/my-selection/facet_line.tpl' )
                )
            );
        }
        else
        {
            return array(
                'content' => array(
                    'articles'    => $tpl->fetch( 'design:esibuild/app_content/my-selection/' . $template . '_line.tpl' ),
                    'articles_nb' => count($managedResults['items']),
                    'num_found'   => $managedResults['total'],
                    'f'           => $tpl->fetch( 'design:esibuild/app_content/my-selection/facet_line.tpl' )
                )
            );
        }
    }
    /**
     * @param array $languages
     * @return array
     */
    public static function getTagFromLanguage( $languages )
    {
        $tags = array();

        foreach( $languages as $language )
            $tags[] = LocaleTool::languageISO639Code( $language );

        return array_unique($tags);
    }
 /**
  * @param array $terms
  * @param string $language
  * @param int $limit
  * @return array
  */
 public static function fetchSolrAutocompleteTerms( $terms = array(), $language = null, $limit = null )
 {
     if( is_null($language) )
         $language = LocaleTool::languageISO639Code();
     
     $filters = array();
     $filters[] = 'meta_installation_id_ms:merck_gs_dictionary';
     $filters[] = 'attr_autocomplete_b:true';
     $filters[] = 'attr_language_code_s:'.$language;
     
     $params = array(    'q'                 => 'attr_term_t:'.implode( ' ', $terms ),
                         'qt'                => 'standard',
                         'wt'                => 'php',
                         'rows'              => $limit,
                         'fq'                => implode( ' AND ', $filters ),
     );
     $result = self::fetchFromSolr( $params, false );
     return $result;
 }
    /**
     * @return eZTemplate
     */
    public function tpl()
    {
        if(is_null($this->_tpl))
        {
            eZTemplate::resetInstance();
            $this->_tpl = eZTemplate::factory();

            if (SolrSafeOperatorHelper::featureIsActive('showMedicalNewsDemo') && SolrSafeOperatorHelper::feature('ShowMedicalNewsDemo', 'showDemo')){
                $showMedicalNewsDemo = true;
                
            }else {
                $showMedicalNewsDemo = false;
            }
            
            $this->_tpl->setVariable('showMedicalNewsDemo',$showMedicalNewsDemo);
            
            $this->_tpl->setVariable('language'          , LocaleTool::languageISO639Code());
            $this->_tpl->setVariable('application_class' , get_class($this) );
            $this->_tpl->setVariable('view_parameters'   , $this->_params['UserParameters']);
            $this->_tpl->setVariable('cluster_identifier', ClusterTool::clusterIdentifier());
            $this->_tpl->setVariable('application_url'   , $this->applicationName());
            $this->_tpl->setVariable('consult'           , $this->isConsult);
            $this->_tpl->setVariable('httpcontext'       , array(
                'host'  => ContextTool::instance()->domain(),
            ));

            $environment = new MMEnvironment();
            $this->_tpl->setVariable('environment'       , $environment->env);

            $applicationLocalized = CacheApplicationTool::buildLocalizedApplication($this->applicationName());

            if (empty($applicationLocalized))
                $this->_tpl->setVariable('application_name'  , $this->applicationName());
            else
            {
                $applicationIdentifier = $applicationLocalized->applicationObject->attribute('identifier');

                $this->_tpl->setVariable('application_name' , $applicationIdentifier );
                $this->_tpl->setVariable('current_localized' , $applicationLocalized );
                $this->_tpl->setVariable('current_application' , $applicationLocalized->applicationObject );
            }
        }

        return $this->_tpl;
    }
    public function htmlBuildResult()
    {
        $lessFiles = SolrSafeOperatorHelper::getLessFiles(
            ($this->app) ? $this->app->applicationObject()->attribute('identifier') : $this->applicationName(),
            $this->app
        );
        $this->tpl()->setVariable( 'applicationLessFiles', $lessFiles );

        if ( !$this->app )
            return;

        if ( $this->app->isFull )
        {
            if ( $this->app->node && $this->app->node instanceof eZContentObjectTreeNode )
            {
                $dataMap     = $this->app->node->dataMap();
                if($dataMap["serialized_taxonomies"]){
                    $taxonomies = $dataMap["serialized_taxonomies"]->content();
                    $publisherPath = $taxonomies["publisher_folder"][0];
                    $publisherFolder = $this->app->applicationLocalized()->getPublisherFolderFromPath($publisherPath);

                    if (isset($taxonomies['language']) && $publisherFolder instanceof PublisherFolder) {
                        $publisherLanguages = $publisherFolder->getLanguages();
                        $languageList = $taxonomies['language'];
                        //$languageTranslations = FacetFilteringTool::getTaxonomyTranslation('language');

                        $availableLanguages = array();

                        foreach (array_keys($this->app->node->object()->allLanguages()) as $locale) {
                            if (is_array($publisherLanguages) && in_array($locale, $publisherLanguages)) {
                                $key = LocaleTool::languageISO639Code($locale);
                                $availableLanguages[$key] = $locale;
                            }
                        }
                    }

                    $uri = eZURI::instance();
                    $uriParams = $uri->UserParameters();
                    if(isset($uriParams['language']))
                        $uriLang = $uriParams['language'];

                    if ($uriLang) {
                        $this->app->node->setCurrentLanguage($uriLang);
                    }
                    if (in_array($publisherLanguages[0], $availableLanguages)){
                        if ($this->app->node->currentLanguage() != $publisherLanguages[0]) {
                            $this->app->node->setCurrentLanguage($publisherLanguages[0]);
                        }
                    }
                }
            }
            
            if ( SolrSafeOperatorHelper::featureIsActive( "SocialSharing" ) && SolrSafeOperatorHelper::feature( "SocialSharing", "EntryExit" ) )
            {
                $this->pushResult( "socialInfos", $this->app->getSocialInfos() );
            }

            if ( $this->app->node instanceof eZContentObjectTreeNode )
                $this->pushResult( "current_node", $this->app->node );
        }
        else if ( $this->app->isSeo )
        {
            $goToSpeciality = null;
            if ( is_null( $this->app->seoParams["speciality"] ) && $this->app->seoParams["noSpeciality"] )
            {
                $goToSpeciality = "all/speciality";
            }

            $this->pushResult( "seoMetas", $this->app->getSeoMetas() );
            $this->pushResult( "doSpecialityRedirect", $goToSpeciality );
        }

    }
 /**
  * @param string $v
  * @return string
  */
 public static function languageCode ( $v )
 {
     return LocaleTool::languageISO639Code($v);
 }
    protected static function updateObject( $contentID, $taxonomies )
    {
        if( !$contentID )
            return;
        
        $remoteId     = 'article_'.$contentID;
        $newTaxonomy  = array();
        
        foreach( $taxonomies as $tId )
        {
            $t          = isset( self::$taxonomyById[$tId] ) ? self::$taxonomyById[$tId] : false;
            $identifier = isset( self::$taxonomyCategoryMapping[$t] ) ? self::$taxonomyCategoryIdentifiers[self::$taxonomyCategoryMapping[$t]] : false;

            if( !$identifier || !$t )
            {
                eZDebug::writeError( "Unable to match taxonomy: remote: $remoteId, taxonomyId: $tId, taxonomy: $t", 'Taxonomies alignment' );
                continue;
            }
        
            if( $identifier == 'conditions' )
                continue;
        
            if( !isset( $newTaxonomy[$identifier]) )
                $newTaxonomy[$identifier] = array();
        
            $newTaxonomy[$identifier][] = $t;
        }
        
        // add publisher and languages
        $newTaxonomy['language'] = array();
        foreach( self::$publishersAndLanguages[$contentID]['lang'] as $locale )
            $newTaxonomy['language'][] = LocaleTool::languageISO639Code( $locale );
        
        $newTaxonomy['publisher_folder'] = array( self::$publisherFolders[self::$publishersAndLanguages[$contentID]['publisher']] );
        
        $sql = sprintf("UPDATE
                            ezcontentobject o,
                            ezcontentobject_attribute a,
                            ezcontentclass_attribute ca
                        SET
                            a.data_text = '%s'
                        WHERE
                            o.remote_id = '%s' AND
                            o.current_version = a.version AND
                            o.id = a.contentobject_id AND
                            a.contentclassattribute_id = ca.id AND
                            ca.identifier = 'serialized_taxonomies'",
            json_encode( $newTaxonomy, true ),
            $remoteId
        );
        self::$dbEz->query( $sql );
    }
    /**
     * @param resource $curlXMLResponse
     * @return array
     */
    protected function processXML($curlXMLResponse)
    {
        //delete existing nodes
        try
        {
            echo "Deleting Previous articles\n";
            $this->deletePreviousArticles();
        }
        catch (Exception $e)
        {
            return null;
        }

        $xml = simplexml_load_string($curlXMLResponse,  null, LIBXML_NOCDATA);
        $xmlArray = json_decode(json_encode($xml), true);

        $i = 0;
        $formattedArticles = array();

        if(isset($xmlArray['channel']))
        {
            if(isset($xmlArray['channel']['item']) && !empty($xmlArray['channel']['item']))
            {
                if(!isset($xmlArray['channel']['item'][0]))
                {
                    $xmlArray['channel']['item'] = array($xmlArray['channel']['item']);
                }

                foreach($xmlArray['channel']['item'] as $article)
                {
                    if($i < 3)
                    {
                        try
                        {
                            $formattedArticle = array(
                                'meta_installation_id_ms'           => keZSolr::installationID(),
                                'meta_guid_ms'                      => md5($article['link'] . $article['category']),
                                'meta_section_id_si'                => 1,
                                'attr_' . ClusterTool::clusterIdentifier() . '_url_s' => $article['link'],
                                'attr_date_dt'                      => $this->formatDate(DATE_RFC2822, $article['pubDate'], "Y-m-d\TH:i:s\Z"),
                                'attr_offline_date_dt'              => '1970-01-01T01:00:00Z',
                                'attr_archive_date_dt'	            => '1970-01-01T01:00:00Z',
                                'attr_headline_t'                   => $article['title'],
                                'attr_headline_lc_s'                => strtolower($article['title']),
                                'attr_promo_description_t'          => empty($article['description']) ? '' : $article['description'],
                                'attr_category_t'                   => empty($article['category']) ? '' : $article['category'],
                                'attr_is_invisible_' . ClusterTool::clusterIdentifier() . '_b'    => false,
                                'subattr_language___source_id____s' => $xmlArray['channel']['language'],
                                'subattr_language_' . ClusterTool::clusterIdentifier() . '____s'              => $xmlArray['channel']['language'],
                                'subattr_publisher_folder___source_id____s'	    => 'congress_report_pt',
                                'meta_language_code_ms'             => LocaleTool::mainLanguage(),
                                'meta_class_identifier_ms'          => 'article',
                                'attr_relative_depth_i'             => 0,
                            );
                            $formattedArticles[] = json_encode($formattedArticle);
                        }
                        catch(Exception $e)
                        {
                            echo "\n Error with item : " , $article['title'] , ' : ' , $e->getMessage() , "\n";
                            continue;
                        }

                        $i++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        echo "|-- $i articles found.\n";
        $this->totalProcessed += $i;

        return $formattedArticles;
    }
    /**
     * @param $curlXMLResponse
     * @return array
     */
    function processXML($curlXMLResponse)
    {
        $xml = simplexml_load_string($curlXMLResponse,  null, LIBXML_NOCDATA);
        $xmlArray = json_decode(json_encode($xml), true);

        $i = 0;
        $formattedArticles = array();

        if(isset($xmlArray['channel']))
        {
            if(isset($xmlArray['channel']['item']) && !empty($xmlArray['channel']['item']))
            {
                if(!isset($xmlArray['channel']['item'][0]))
                {
                    $xmlArray['channel']['item'] = array($xmlArray['channel']['item']);
                }

                foreach($xmlArray['channel']['item'] as $article)
                {
                    try
                    {
                        if( !isset($article['dateStart']) || !$article['dateStart'] )
                        {
                            $article['dateStart'] = $this->formatDate('d-m-Y H:i:s O', $article['pubDate'], "Y-m-d\TH:i:s\Z");
                        }
                        if(  !isset($article['dateEnd']) || !$article['dateEnd'] )
                        {
                            $article['dateEnd'] = $this->formatDate('d-m-Y H:i:s O', $article['pubDate'], "Y-m-d\TH:i:s\Z");
                        }

                        $formattedArticle = array(
                            'meta_installation_id_ms'           => keZSolr::installationID(),
                            'meta_path_si'                      => $this->getMetaPathId(),
                            'meta_guid_ms'                      => md5($this->applicationIdentifier . $article['guid']. $article['link']),
                            'meta_remote_id_ms'                 => md5($this->applicationIdentifier . $article['guid']. $article['link']),
                            'meta_section_id_si'                => 1,
                            'attr_' . ClusterTool::clusterIdentifier() . '_url_s' => md5($this->applicationIdentifier . $article['guid']. $article['link']),
                            'attr_date_dt'                      => $this->formatDate('d-m-Y H:i:s O', $article['pubDate'], "Y-m-d\TH:i:s\Z"),
                            //'attr_article_date_dt'              => $this->formatDate('d-m-Y H:i:s', $article['pubDate'], "Y-m-d\TH:i:s\Z"),
                            //'attr_article_year_i'               => $this->formatDate('d-m-Y H:i:s', $article['pubDate'], "Y"),
                            //'attr_article_month_i'              => $this->formatDate('d-m-Y H:i:s', $article['pubDate'], "m"),
                            'attr_date_start_dt'                => $this->formatDate('d-m-Y H:i:s', $article['dateStart'], "Y-m-d\TH:i:s\Z"),
                            'attr_article_year_start_i'         => $this->formatDate('d-m-Y H:i:s', $article['dateStart'], "Y"),
                            'attr_article_month_start_i'        => $this->formatDate('d-m-Y H:i:s', $article['dateStart'], "m"),
                            'attr_date_end_dt'                  => $this->formatDate('d-m-Y H:i:s', $article['dateEnd'], "Y-m-d\TH:i:s\Z"),
                            'attr_article_year_end_i'           => $this->formatDate('d-m-Y H:i:s', $article['dateEnd'], "Y"),
                            'attr_article_month_end_i'          => $this->formatDate('d-m-Y H:i:s', $article['dateEnd'], "m"),
                            'attr_offline_date_dt'              => '1970-01-01T01:00:00Z',
                            'attr_archive_date_dt'	            => '1970-01-01T01:00:00Z',
                            'attr_headline_t'                   => $article['title'],
                            'attr_headline_s'                   => $article['title'],
                            'attr_headline_lc_s'                => strtolower($article['title']),
                            'attr_promo_description_t'          => empty($article['description']) ? '' : $article['description'],
                            'attr_is_invisible_' . ClusterTool::clusterIdentifier() . '_b'    => false,
                            'subattr_speciality___source_id____s'        => $this->specialityIds,
                            'subattr_language___source_id____s'             => $xmlArray['channel']['language'],
                            'subattr_language_' . ClusterTool::clusterIdentifier() . '____s'              => $xmlArray['channel']['language'],
                            'subattr_local_application___source_id____s'    => $this->application->application_id,
                            'subattr_local_application___source_mixed____s' => $this->getAllApplicationLocalizedIds(),
                            'subattr_publisher_folder___source_id____s'	    => $this->getPublisherFolderPath(),
                            'meta_language_code_ms'     => LocaleTool::mainLanguage(),
                            'meta_class_identifier_ms' => 'article',
                            'attr_content_rating_'. ClusterTool::clusterIdentifier() .'_f'  =>  0,
                            'attr_view_counter_'. ClusterTool::clusterIdentifier() .'_i'    =>  0,
                            'attr_evrika_address_city_s'         => trim($article['address']),
                            'subattr_evrika_specialty____s'          => array_map(function($item) { return trim($item); }, array_filter(explode(';', $article['specialties']), function($item) { return strlen(trim($item)) > 0; })),
                            'attr_evrika_address_city_t_ru'      => trim($article['address']),
                        );
                        $formattedArticles[] = json_encode($formattedArticle);
                        $i++;
                    }
                    catch(Exception $e)
                    {
                        echo "\n Error with item guid : " , $article['guid'] , ' : ' , $e->getMessage() , "\n";
                        continue;
                    }
                }
            }
        }

        echo "|-- $i articles found.\n";
        $this->totalProcessed += $i;

        return $formattedArticles;
    }
    /**
     * @param string $taxonomyCategory
     * @param float $taxonomyValue
     * @param int $limit
     * @param boolean $includeAllValues
     * @return array
     */
    public function getRelatedContent($taxonomyCategory, $taxonomyValue, $limit, $includeAllValues, $nodeId)
    {
        $fields = $this->mappingFieldsSolr;

        $filters = array();
        if ($includeAllValues)
        {
            foreach ($taxonomyValue as $tv)
            {
                $filters[] =  "subattr_{$taxonomyCategory}___source_id____s: \"{$tv}\"";
            }
        }
        else
        {
            $filter = "subattr_{$taxonomyCategory}___source_id____s: (%s)";
            $taxonomyValue = array_map( function($v) {
                return "\"{$v}\"";
            }, $taxonomyValue);
            $filter = sprintf($filter, implode(' OR ', $taxonomyValue));

            $filters[] = $filter;
        }

        $filters[] = '-meta_node_id_si: ' . $nodeId;
        $locale = LocaleTool::languageFromLocale();
        $filters[] = "meta_language_code_ms:".$locale.'*';

        $params = array(
            'indent'        => 'on',
            'q'             => '*:*',
            'fq'            => implode(' AND ' , $filters),
            'start'         => $this->offset,
            'rows'          => $limit,
            'fl'            => implode(',',$fields),
            'qt'            => 'ezpublish',
            'explainOther'  => '',
            'hl.fl'         => '',
            'sort'          => "attr_online_date_dt desc",
        );

        $solrResult =  SolrTool::rawSearch( $params, 'php', true, false );

        foreach ( $solrResult['response']['docs'] as $doc )
        {
            $nodeId                     = $doc['meta_node_id_si'][0];
            $articleNodeIDs[]           = $nodeId;
            $solrApplicationIndexes     = isset ( $doc[$fields['apps']] ) ? $doc[$fields['apps']] : array();
            $solrApplicationNames       = array();
            $solrApplicationIdentifiers = array();
            $app                        = null;

            foreach( $solrApplicationIndexes as $applicationIndex )
            {
                list ( $cluster, /* unused */, $applicationId ) = explode( '##', $applicationIndex );

                if ( $cluster == ClusterTool::clusterIdentifier() )
                {
                    $app = CacheApplicationTool::buildLocalizedApplicationByApplication( $applicationId );

                    if ( !($app instanceof ApplicationLocalized) )
                        continue;

                    $solrApplicationNames[] = $app->attribute('name');
                    $solrApplicationIdentifiers[] = $app->applicationObject()->attribute('identifier');
                }
            }

            $url = isset( $doc[$fields['url']] ) ? $doc[$fields['url']] : null;

            if ( empty( $solrApplicationIdentifiers ) )
            {
                eZDebug::writeError( "Could not get application id for cluster for node $nodeId - Falling back to current application" );
                $solrApplicationIdentifiers = array( $this->contentList->applicationObject()->attribute('identifier') );
            }

            $masterApps = $this->contentList->iniMerck()->hasSection('MasterAppSettings') && $this->contentList->iniMerck()->hasVariable( 'MasterAppSettings', 'MasterAppList' )
                ? $this->contentList->iniMerck()->variable( 'MasterAppSettings', 'MasterAppList' )
                : array();

            $applicationIdentifier = $solrApplicationIdentifiers[0];

            if (!empty($masterApps))
            {
                foreach ($solrApplicationIdentifiers as $solrApplicationIdentifierKey => $solrApplicationIdentifier)
                {
                    if (in_array($solrApplicationIdentifier, $masterApps))
                    {
                        $applicationIdentifier = $solrApplicationIdentifier;
                        unset( $solrApplicationIdentifiers[$solrApplicationIdentifierKey] );
                        $solrApplicationIdentifiers = array_merge( array( $applicationIdentifier ), $solrApplicationIdentifiers );

                        break;
                    }
                }
            }

            $application       = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );
            $applicationObject = $application->applicationObject();
            $applicationType   = $applicationObject->applicationType()->attribute('type_identifier');
            $publisherPath     = $doc[$fields['publisher_path']][0];
            $publisherInfo     = PublisherFolderTool::getPathToIDMapping($publisherPath);
            $publisherFolderId = $publisherInfo['pfid'];
            $onlineDateStamp   = strtotime($doc[$fields['online_date']]) > 3600*24*2 ? SolrTool::getTimestampFromSolr($doc[$fields['online_date']]) : 0;
            $mediaTypes        = isset( $doc[$fields['media_types']] )
                ? json_decode( base64_decode($doc[$fields['media_types']]), true )
                : array();
            $mediaCount        = 0;
            $hasImage          = isset( $doc[$fields['has_image']] )
                ? json_decode( base64_decode($doc[$fields['has_image']]), true )
                : array();
            $url               = ($applicationType == 'first-child')
                ? $application->attribute('url_alias')
                : $application->attribute('url_alias') . '/' . $publisherFolderId . '/' . $url;

            $result[$nodeId] = array(
                'object_id'            => isset( $doc[$fields['object_id']] )            ? $doc[$fields['object_id']]            : null,
                'language'             => isset( $doc[$fields['language']] )             ? $doc[$fields['language']]             : null,
                'headline'             => isset( $doc[$fields['headline']] )             ? $doc[$fields['headline']]             : null,
                'promo_description'    => isset( $doc[$fields['promo_description']] )    ? $doc[$fields['promo_description']]    : null,
                'online_date'          => strtotime($doc[$fields['online_date']]) > 3600*24*2 ? SolrTool::getDateFromSolr($doc[$fields['online_date']]) : 0,
                'has_image'            => $hasImage,
                'url'                  => $url,
                'node_id'              => $nodeId,
                'internal_id'          => isset( $doc[$fields['internal_id']] )          ? $doc[$fields['internal_id']]            : null,
                'application'          => $application,
            );
        }
        return $result;
    }
    /**
     * @return bool
     */
    public function htmlBuildFullResult()
    {
        /* @type $dataMap eZContentObjectAttribute[] */
        /* @type $publisherNode eZContentObjectTreeNode */
        $article_parameters = $this->_params['UserParameters'];
        $dataMap            = $this->node->dataMap();
        $taxonomies         = $dataMap["serialized_taxonomies"]->content();
        $publisherPath      = $taxonomies["publisher_folder"][0];
        $publisherFolder    = $this->applicationLocalized()->getPublisherFolderFromPath( $publisherPath );

        $this->initChannelInformations();
        $this->pushChannelResult();
        
        if(isset($article_parameters['language']))
        {
            $this->node->setCurrentLanguage($article_parameters['language']);
        }
        
        $this->pushResult('article_parameters', $article_parameters);
        $this->pushResult('node'              , $this->node);
        $this->pushResult('features'          , $this->resultHandler->features);
        $this->pushResult('publisher'         , $publisherFolder);

        // get all languages avalaible for the node
        /* @type $dataMap eZContentObjectAttribute[] */
        $languages  = array();
        $dataMap    = $this->node->dataMap();
        $serial     = $dataMap['serialized_taxonomies']->content();

        if( isset($serial['language']) && $publisherFolder instanceof PublisherFolder )
        {
            $publisherLanguages   = $publisherFolder->getLanguages();
            $languageList         = $serial['language'];
            $languageTranslations = FacetFilteringTool::getTaxonomyTranslation('language');

            // get locales and iso of languages node
            $availableLanguages = array();

            foreach( array_keys($this->node->object()->allLanguages()) as $locale )
            {
                if ( is_array($publisherLanguages) && in_array($locale, $publisherLanguages) )
                {
                    $key                      = LocaleTool::languageISO639Code($locale);
                    $availableLanguages[$key] = $locale;
                }
            }

            // compare iso with the ez tag for get the name
            foreach($languageList as $languageItem)
            {
                if(isset($availableLanguages[$languageItem]))
                {
                    $languages[] = array(
                        'locale' => $availableLanguages[$languageItem],
                        'name'   => $languageTranslations[$languageItem]
                    );
                }
            }
        }
        
        $uri = eZURI::instance();
        $uriParams = $uri->UserParameters();
        if(isset($uriParams['language']))
            $uriLang = $uriParams['language'];
        
        if($uriLang){
            $this->node->setCurrentLanguage($uriLang);
            $this->pushResult('current_language', $uriLang);
            $this->pushResult('node', $this->node);
        }
        elseif(in_array($publisherLanguages[0], $availableLanguages)){
            if($this->node->currentLanguage() != $publisherLanguages[0]){
                $this->node->setCurrentLanguage($publisherLanguages[0]);
                $this->pushResult('current_language', $publisherLanguages[0]);
                $this->pushResult('node', $this->node);
            }
        }
        else{
            $this->pushResult('current_language'  , $this->node->currentLanguage());
            $this->pushResult('node', $this->node);
        }
        
        $this->pushResult('languages', $languages);

        if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
            $this->pushResult( 'gtm_variables', $this->getGTMTags( $this->node ) );

        $this->pushResult('related_publishers', $this->getRelatedPublishers());
        $this->pushResult('related_content', $this->getRelatedContent($this->node));
        $this->pushResult('related_content_taxonomy', $this->getCustomParameter('RelatedContentTaxonomy'));
        return true;
    }
    /**
     * @return array
     */
    private function entryExitPage()
    {
        header('esi-enabled: 1');
        $skipPage = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'SkipExitPage', 'application');
        $noFullView = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'NoFullView', 'application');

        $restrictionLevel = $this->applicationLocalized()->restrictionLevel();
        if(
            ( !isset($_GET['key']) &&  $this->applicationObject()->hasExternalLinkHandler() && $skipPage ) 
            || ( !(bool)self::user() &&  !isset($_GET['key']) && ($restrictionLevel == ApplicationObject::RESTRICTION_LEVEL_RESTRICTED) )
          )
        {
            $patterns   = array(
                '#^(?:https?://[^/]+)?/esibuild/main_view/app_content#',
                '#\?key=[^&]+#'
            );
            $context = ContextTool::instance()->domain().preg_replace($patterns, array( '', '' ), $_SERVER['REQUEST_URI'] );
            $context = preg_replace( '#/external/#', '/', $context );
            header( 'Location: '.$context );
            eZExecution::cleanExit();
        }

        $Result               = array();
        $Result['pagelayout'] = 'esibuild/app_content/pagelayout.tpl';
        $templateContent      = 'esibuild/app_content/external/restricted.tpl';
        if ( $this->isFull )
        {
            $Result['pagelayout'] = ContextTool::instance()->isMobile()
                ? 'esibuild/app_content/pagelayout.tpl'
                : 'esibuild/app_content/full/pagelayout.tpl';

            $templateContent = 'esibuild/app_content/default/restricted.tpl';

            $this->initChannelInformations();
            $this->pushChannelResult();
        }

        foreach ( $this->_result as $variableName => $variableValue )
            $this->tpl()->setVariable( $variableName, $variableValue );

        $instance = self::instance();

        if ( $instance->node && $instance->node instanceof eZContentObjectTreeNode )
        {
            $dataMap = $instance->node->dataMap();
            if( isset($dataMap["serialized_taxonomies"]) )
            {
                $taxonomies = $dataMap["serialized_taxonomies"]->content();
                $publisherPath = $taxonomies["publisher_folder"][0];
                $publisherFolder = $instance->applicationLocalized()->getPublisherFolderFromPath($publisherPath);
            }

            if (isset($taxonomies['language']) && $publisherFolder instanceof PublisherFolder) {
                $publisherLanguages = $publisherFolder->getLanguages();
                $languageList = $taxonomies['language'];

                $availableLanguages = array();

                foreach (array_keys($instance->node->object()->allLanguages()) as $locale) {
                    if (is_array($publisherLanguages) && in_array($locale, $publisherLanguages)) {
                        $key = LocaleTool::languageISO639Code($locale);
                        $availableLanguages[$key] = $locale;
                    }
                }
            }

            if (in_array($publisherLanguages[0], $availableLanguages)){
                if ($instance->node->currentLanguage() != $publisherLanguages[0]) {
                    $instance->node->setCurrentLanguage($publisherLanguages[0]);
                }
            }
        }
        
        $this->tpl()->setVariable( 'application', $this->applicationObject );
        $this->tpl()->setVariable( 'node', $instance->node );

        $patterns   = array(
            '#^(?:https?://[^/]+)?/esibuild/main_view/app_content#',
            '#\?key=[^&]+$#',
            '#\?key=[^&]+&#'
        );

        $appURL = preg_replace($patterns, array( '', '', '?' ), $_SERVER['REQUEST_URI'] );
        $context = $skipPage ? ContextTool::instance()->domain().'/external'.$appURL : ContextTool::instance()->domain().$appURL;

        // In case we are on application without full view like GP Notebook on UK
        if($noFullView)
        {
            $context = ContextTool::instance()->domain();
        }

        $this->tpl()->setVariable( 'context', urlencode( $context ) );

        if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
        {
            $this->tpl()->setVariable( 'gtm_variables', $this->getGTMTags( $instance->node ) );
            if( $instance->node )
            {
                $publisherNode = NodeTool::getPublisherNodeFromNode($instance->node);
                if ($publisherNode)
                {
                    /* @type eZContentObjectAttribute[] $publisherDM */
                    $publisherDM   = $publisherNode->dataMap();
                    $publisherPath = $publisherDM['path']->content();
                    $this->tpl()->setVariable( 'publisher', $this->applicationLocalized()->getPublisherFolderFromPath( $publisherPath ) );
                }
            }
        }

        $Result['content'] = $this->tpl()->fetch( "design:$templateContent" );

        return $Result;
    }
    public function contentBuildResult()
    {
        $oldSkipPage = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'SkipExitPage', 'application');
        $skipPage = $oldSkipPage || !$this->exitStrategy();

        $this->pushResult('user' , self::user());
        $this->pushResult('country', LocaleTool::countryISO3166Code());

        if ( $skipPage )
        {
            $_REQUEST['proceed'] = 'proceed';
            $_COOKIE[$this->cookieKey()] = '1';
            if ( ContextTool::instance()->isMobile() )
                $_REQUEST['r'] = 1;
        }

        if( isset($_REQUEST['proceed']) && isset($_COOKIE[$this->cookieKey()]) && filter_var($_COOKIE[$this->cookieKey()], FILTER_VALIDATE_INT))
        {
            // proceed to iframe view
            $this->iframeBuildResult( );
        }
        elseif( isset($_REQUEST['proceed']) )
        {
            // proceed requested but no cookie, we ask again and force redirect to make sure we the proper layout
            header('Location: '.ContextTool::instance()->domain().$this->applicationLocalized()->applicationUrl());
            eZExecution::cleanExit();
        }
        else
        {
            // normal exit page vie
            $isMobile   = ContextTool::instance()->isMobile();
            $urlToRedirect = isset($_REQUEST['r']) ? trim($_REQUEST['r']) : null;
            if ($this->isExitApplication() && $this->displayIframe())
            {
                $serverUrl  = ContextTool::instance()->domain();
                $params = array(
                    'r' => urlencode($urlToRedirect),
                    'exit_strategy' => 0,
                    'display_iframe' => $this->displayIframe(),
                    'new_window' => $this->newWindow()
                );

                $urlToRedirect = $serverUrl . '/external/exit/?' . http_build_query($params);
                $this->pushResult('decode_url', false);
                $this->pushResult('server_url', $serverUrl);
            }
            if($isMobile){
                if($this->applicationObject()->externalLinkHandler())
                {
                    $externalUrl = $this->applicationObject()->externalLinkHandler()->getNodeUrl( $this->node );
                    $urlToRedirect = isset($externalUrl) ? $externalUrl : $urlToRedirect ;

                    if(SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, 'usePostMethod', 'application' )){

                        $url = $this->applicationObject()->externalLinkHandler()->getNodeUrl( $this->node );
                        $url = $this->getDeeplink( $url );

                        if ($url == null && isset($_REQUEST['r']))
                        {
                            $url = urldecode($_REQUEST['r']);
                        }

                        $url = in_array('arg', array_keys($this->_params['UserParameters'])) ? $url . $this->_params['UserParameters']['arg'] : $url;

                        $this->pushResult('postParams', $url);
                    }
                }
                else
                {
                    $urlToRedirect = '/bad_config';
                }
            }
            $this->pushResult('back_url', ContextTool::instance()->backUrl());
            $this->pushResult('url', $urlToRedirect);
            $this->pushResult('deeplink', urlencode( $this->getDeeplink() ));
            // Because we are passing boolean parameters to final URL, we need to make isset check.
            if ( $this->isDeeplinkApplication() || $this->isExitApplication() )
            {
                if ( isset( $_GET['display_iframe'] ) )
                {
                    $this->pushResult('display_iframe', $this->displayIframe());
                }
                if ( isset( $_GET['new_window'] ) )
                {
                    $this->pushResult('new_window', $this->newWindow());
                }
                if ( isset( $_GET['exit_strategy'] ) )
                {
                    $this->pushResult('exit_strategy', $this->exitStrategy());
                }
            }
        }

        if($this->node && $this->node->attribute('url_alias') != "")
        {
            $this->pushResult('article_url', end(explode("/", $this->node->attribute('url_alias'))));
            /* @type $pfDM eZContentObjectAttribute[] */
            $pf   = NodeTool::getPublisherNodeFromNode( $this->node );
            $pfDM = $pf->DataMap();
            $pfID = PublisherFolderTool::getPathToIDMapping( $pfDM['path']->content() );
            $this->pushResult( 'pfid', $pfID['pfid'] . '/' );
        }

        $oldOpenInNewWindow = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject()->identifier, 'openInNewWindow', 'application');
        $openInNewWindow = $this->newWindow() || $oldOpenInNewWindow;
        $this->pushResult('application', $this->applicationObject);
        $this->pushResult('open_in_new_window', $openInNewWindow);
        $this->pushResult('cookie_key', $this->cookieKey());
        $this->pushResult('node', $this->node);
        
        if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
        {
            $this->pushResult( 'gtm_variables', $this->getGTMTags( $this->node ) );
            if( $this->node )
            {
                $publisherNodeId = PublisherFolderTool::getPublisherNodeIdFromArticleNode($this->node);

                if ($publisherNodeId)
                {
                    $publisherInfos  = PublisherFolderTool::getNodeIdToPathMapping( $publisherNodeId );
                    $publisherPath   = $publisherInfos['path'];

                    $this->pushResult( 'publisher', $this->applicationLocalized()->getPublisherFolderFromPath( $publisherPath ) );
                }
            }
        }
    }
    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();
    }