/**
     * @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];
                }
            }
        }
    }
    /**
     * @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;
    }
    /**
     * @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 );
        }

    }
    /**
     * @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;
    }
    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 string $v
  * @return string
  */
 public static function languageCode ( $v )
 {
     return LocaleTool::languageISO639Code($v);
 }
    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();
    }