/**
     * @return array
     */
    public function additionalSolrFilters()
    {
        $filters = array();
        
        if( !$this->contentList->isFull )
        {
            //Show only last article (HTML)
            if( $this->contentList->getOutputType() == 'html' )
            {
                $this->limit = 99;
                $filters[]   = 'attr_date_dt:[NOW-7DAY/DAY TO NOW]';
            }
            //Exclude last articles (JSON)
            elseif( count( $this->excludeIds ) > 0 )
            {
                if (!SolrSafeOperatorHelper::featureIsActive('jamaNetworkListView'))
                {
                    $filters[] = '-meta_node_id_si:(' . implode(' OR ', $this->excludeIds) . ')';
                }
            }

        }

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

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

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

        // Fires a request to get user profile data
        return WSHelper::call( "read", $readParameters );
    }
    /**
     * @return string
     */
    protected function validateToU()
    {
        if( !self::user() )
            return false;

        self::user()->toUValidated(true);

        $context = ContextTool::instance()->backUrl();
        $context = isset( $_POST['context'] ) ? $_POST['context'] : '/';

        // @todo: update ESB by sending validation status
        $esbResult = new ESBResult();
        $userService = ESBFactory::getUserService();

        if(SolrSafeOperatorHelper::featureIsActive('UUMP'))
        {
            
            $result = $userService->read(self::user()->attribute('uuid'));
            ServiceLoginUUMP::populateESBResult($esbResult, $result);
        }
        else
        {
            $result = ServiceLogin::readCall(self::user()->attribute('uuid'), $esbResult);
            ServiceLogin::populateESBResult($esbResult, $result);
        }

        $esbResult->userName = self::user()->attribute('uuid');
        $esbResult->termsOfUse = 'Y';
        $esbResult->privacyPolicy = 'Y';

        if( SolrSafeOperatorHelper::featureIsActive('UUMP') || (ClusterTool::clusterIdentifier() == "cluster_at") )
        {
            $esbResult->termsOfUse = '1';
            $esbResult->privacyPolicy = '1';
        }
        $esbResult->countryOfRegistration = self::user()->attribute( 'country' );

        $userService->write($esbResult->toServiceAgreementTicket());

        // if the ESB call fails, we still validate the user input to let him access the content
        $esbResult->forceToUValidated = true;
        $esbResult->sessionID = $_COOKIE[self::iniMerck()->variable('TIBCOCookieSettings', 'TIBCOCookieName')];

        $loginResult = MMUserLogin::esbLogin( self::user()->attribute('uuid'), $esbResult, false, $context );
        if ( $loginResult )
        {
            // Stringify params
            $strParams = json_encode( $loginResult['params'] );

            // Encrypts params
            $encryptedParams = MMUserLogin::encryptText( $strParams );
            // Redirect to PHP-ESI
            $redirectURL = ContextTool::instance()->domain()."/loginActions.php?context=" . urlencode( $loginResult['destUrl'] ) . "&params=" . urlencode( $encryptedParams );
        
            return $redirectURL;
        }
    }
    public function __construct()
    {
        // Guzzle RESTclient
        $wsUrl = SolrSafeOperatorHelper::clusterIni('WebService', 'BaseUrlUUMP', 'merck.ini') . SolrSafeOperatorHelper::clusterIni('WebService', 'Prefix', 'merck.ini');
        $this->client = new Client( $wsUrl );

        // Logger
        $filter           = new ezcLogFilter();
        $filter->severity = ezcLog::ERROR | ezcLog::INFO | ezcLog::WARNING;
        $this->logger     = ezcLog::getInstance();
        $this->logger->getMapper()->appendRule( new ezcLogFilterRule( $filter, new ezcLogUnixFileWriter( "var/log/", "esb_uump.log", 157286400, 3 ), true ) );
    }
    /**
     * @param string $facetAttribute attribute field from FacetField class
     * @return string[] list of taxonomies
     */
    static function getForcedCheckedTaxonomy( $facetAttribute )
    {
        if (SolrSafeOperatorHelper::featureIsActive('FacetTaxonomy')) {
            $forcedCheckedFeatureValues = SolrSafeOperatorHelper::feature('FacetTaxonomy','ForcedCheckedFacetTaxonomy');

            if ( isset($forcedCheckedFeatureValues[$facetAttribute]) ) {
                return explode(';', $forcedCheckedFeatureValues[$facetAttribute][0]);
            }
        }

        return array();
    }
    /**
     * @param eZContentObjectTreeNode $node
     * @return string
     */
    public function getNodeUrl(&$node = null)
    {
        if(!SolrSafeOperatorHelper::featureIsActive("GPNotebook"))
        {
            return $this->application()->applicationLocalized()->attribute( 'external_url' );
        }

        $urlParams = array(
            'data' => SolrSafeOperatorHelper::getAndStoreGPNotebookHS(),
        );

        return array( 'url' => $this->application()->applicationLocalized()->attribute( 'external_url' ), 'params' => $urlParams );
    }
    public function __construct()
    {
        $ini = eZINI::instance( 'merck.ini' );

        if( $ini->hasVariable( 'ActiveMQ', 'BrokerUrl' ) )
        {
            $this->messageBrokerUrl = $ini->variable( 'ActiveMQ', 'BrokerUrl' );
        }
        else
        {
            $this->messageBrokerUrl = SolrSafeOperatorHelper::feature( 'AsynchronousAnalyticsLoginCall', 'BrokerUrl' );
        }
        $this->queuePrefix = SolrSafeOperatorHelper::feature( 'AsynchronousAnalyticsLoginCall', 'QueuePrefix' );
    }
    /**
     * @param string $attribute
     * @return array
     */
    public static function getMapping($attribute)
    {
        $solrField = "attr_{$attribute}_dt";

        $overrideFacetPublischedIsActive = SolrSafeOperatorHelper::featureIsActive('PublishedDateFacetCustom');
        if ($overrideFacetPublischedIsActive)
        {
            $appIdentifier = SolrSafeOperatorHelper::feature('PublishedDateFacetCustom', 'ApplicationIdentifier');
            if($appIdentifier[0] == self::$applicationIdentifier)
            {
                return array(
                    array(
                        'label' => 'date-3',
                        'query' => "$solrField:[NOW-3DAYS/DAY TO *]"
                    ),
                    array(
                        'label' => 'date-7',
                        'query' => "$solrField:[NOW-7DAYS/DAY TO *]"
                    ),
                    array(
                        'label' => 'all',
                        'query' => "$solrField:[NOW-15DAYS/DAY TO *]"
                    ),
                );
            }
        }
        else
        {
            return array(
                array(
                    'label' => 'date-7',
                    'query' => "$solrField:[NOW-7DAYS/DAY TO *]"
                ),
                array(
                    'label' => 'date-30',
                    'query' => "$solrField:[NOW-30DAYS/DAY TO *]"
                ),
                array(
                    'label' => 'date-90',
                    'query' => "$solrField:[NOW-90DAYS/DAY TO *]"
                ),
                array(
                    'label' => 'date-365',
                    'query' => "$solrField:[NOW-1YEAR/DAY TO *]"
                ),
            );
        }
    }
    /**
     * @return int
     */
    private function getLimit()
    {
        $limit = 10;

        if(SolrSafeOperatorHelper::clusterHasFeaturedChannel())
            $limit = 5;

        elseif ( $this->_application
            && $this->_application->applicationObject->configurationContentService
            && $this->_application->applicationObject->configurationContentService->hasAttribute('most_column_limit') )
        {
            $limit = $this->_application->applicationObject->configurationContentService->attribute('most_column_limit');
        }

        return $limit;
    }
    public function __construct()
    {
        // Guzzle RESTclient
        $this->builder = ServiceBuilder::factory(__DIR__ . '/../../classes/service/descriptor.php');


        $this->client = $this->builder['ldap'];

        // Logger
        $filter = new ezcLogFilter();
        $filter->severity = ezcLog::ERROR | ezcLog::INFO | ezcLog::WARNING;
        $this->logger = ezcLog::getInstance();
        $logFileName = "ws.log";
        if ( SolrSafeOperatorHelper::clusterIni('WebService', 'CountrySpecificLogs', 'merck.ini') == 'enabled' )
        {
            $clusterId = ClusterTool::clusterIdentifier();
            $logFileName = "ws_{$clusterId}.log";
        }
        $this->logger->getMapper()->appendRule(new ezcLogFilterRule( $filter, new ezcLogUnixFileWriter( "var/log/", $logFileName, 157286400, 3 ), true ) );
    }
 /**
  * @return void
  */
 public function htmlBuildResult()
 {
     $this->initChannelInformations();
     $this->pushChannelResult();
     
     if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
     {
         $this->pushResult( 'gtm_variables', $this->getGTMTags());
     }
     
     switch (true)
     {
         case $this->isSearchPage():
             return $this->htmlBuildListResult();
             break;
         case $this->isDetailsPage():
             return $this->htmlBuildFullResult();
             break;
     }
 }
    /**
     * @param array $postData
     * @throws Exception
     * @throws ezcLogWriterException
     */
    private static function configCurlClient($postData)
    {
        if( SolrSafeOperatorHelper::featureIsActive( 'OverrideWSHandler' ) )
        {
            $hostUrl = SolrSafeOperatorHelper::feature('OverrideWSHandler', 'Url');
            self::instance()->logger->log("BaseUrl :" .$hostUrl, ezcLog::INFO);

            curl_setopt_array(self::instance()->client(), array(
                CURLOPT_URL => $hostUrl,
                CURLOPT_POST => TRUE,
                CURLOPT_HTTP_VERSION =>	CURL_HTTP_VERSION_1_1,
                CURLOPT_RETURNTRANSFER => TRUE,
                CURLOPT_HTTPHEADER => array(
//                    $hostUrl,
                    'Content-Type: application/json',
                    'AuthKey: dcec0748-e4a4-40da-bcee-b2f9f794af55'
                ),
                CURLOPT_POSTFIELDS => json_encode(self::mapESBDataToWS($postData))
            ));
        }
    }
    /**
     * Form submission handler for sending sms
     *
     * @return bool
     */
    public function sm()
    {
        $http = BlockDefault::http();
        $researchType = $http->hasPostVariable( 'typeOfResearch' ) ? stripslashes( $http->postVariable( 'typeOfResearch' ) ) : '';
        if(!empty($researchType)){
            $this->researchType = $researchType;
            $this->recipientEmail = SolrSafeOperatorHelper::getCustomParameter($this->applicationObject->identifier, $this->researchType, 'application');
        }

        if(empty($this->senderEmail) || empty($this->recipientEmail)){
            return false;
        }

        $message = $this->prepareMessageText();
        $mailObject = $this->prepareMailObjectText();

        $email = new MailTool( $mailObject, $this->senderEmail, $this->recipientEmail, $message, self::DOC_REQUEST_LOG_NAME);
        return $email->sendMail();

        return $sendStatus;
    }
    /**
     * @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];
                }
            }
        }
    }
    protected function checkRead( $username )
    {
        $postData = array(
            'Username'      => $username,
            'Params'    => $this->_clusterMerckIni->variable( 'EsbSettings', 'AvailableParams' )
        );
        if( !in_array( 'Registration_date', $postData['Parameters']) && \SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
            $postData['Params'][] = 'Registration_date';

        return $this->checkESBMethod( '/Profile/Read', json_encode( array( 'Data' => $postData ) ) );
    }
    $displayToUPPAndOptInsBlockTitle = in_array( ClusterTool::clusterIdentifier(), array( 'cluster_france' ) );
    
    $visitorCountry = SolrSafeOperatorHelper::getLocaleBySystemCode( 'ga_visitor_country' );
    if( $visitorCountry == 'not provided' || !isset($visitorCountry) || is_null($visitorCountry) || empty($visitorCountry)){
        
        $dt = new DateTime("Europe/Warsaw");
        $msg = 'Missing ga_visitor_country for '.ClusterTool::clusterIdentifier().' at '.$dt->format('Y-m-d H:i:s');
        ezLog::write($msg, 'toupp_visitor_country.log');
    }

    echo json_encode( array(
        'userProfile'      => $userProfile,
        'displayConsents'  => $displayConsents,
        'useDedicatedPage' => (ContextTool::instance()->isMobile() ? SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPageMobile' ) : SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPage' )),
        'visitorCountry'   => SolrSafeOperatorHelper::getLocaleBySystemCode( 'ga_visitor_country' ),
        'staticPages'      => array(
            'ToU' => is_null( $touPage ) ? null : $touPage->attribute( 'core_content' ),
            'PP'  => is_null( $ppPage ) ? null : $ppPage->attribute( 'core_content' )
        ),
        'features'         => array(
            'currentToUConsentVersion'        => $currentToUConsentVersion,
            'currentPPConsentVersion'         => $currentPPConsentVersion,
            'hasCheckbox'                     => $hasCheckbox,
            'precheckedCheckbox'              => $precheckedCheckbox,
            'adaptConsentText'                => $adaptConsentText,
            'isConsentOptOut'                 => $isConsentOptOut,
            'displayToUPPAndOptInsBlockTitle' => $displayToUPPAndOptInsBlockTitle,
            'touPPCheckboxFeatures'           => $touPPCheckboxFeatures,
            'optInFeatures'                   => $optInFeatures,
        )
<?php

/**
 * The CRON will parse all clusters and check if feature is active
 * Make a CURL on the URL
 * If the content is valid and has at least 1 entry -> erase all children of the NodeID
 * Create a child for each entries with the HTML provided by UltraNoir and with info provided by the RSS
 */

$xmlUrl = '';

if(SolrSafeOperatorHelper::featureIsActive('CongressReportRss'))
{
    $xmlUrl = SolrSafeOperatorHelper::feature('CongressReportRss', 'Url');
}
else
{
    $cli = eZCLI::instance();
    $cli->output( 'Feature "CongressReportRss" not found' );
}

$congressReportRss = new CongressReportRss($xmlUrl);
$congressReportRss->importXMLToDatabase();
    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 ) );
                }
            }
        }
    }
    /**
     * i18n operator works like : source|context([argument1, argument2 ...])
     * Arguments are optional and are comma separated
     *
     * @return Callable[]
     *
     * Examples :
     *
     * Simple without argument:
     * {{# i18n }}
     *   MORE|merck()
     * {{/ i18n }}
     *
     * Or with argument:
     * {{# i18n }}
     *   %nb RESULTS|merck(3)
     * {{/ i18n }}
     */
    private static function getHelpers($application = null)
    {
        return array(
            'i18n' => function($text) {
                preg_match("#(?<source>[^\|]+)\|(?<context>[^(]+)\((?<params>[^\)]+)?\)#", $text, $m);
                if($m && $m["source"] && $m["context"])
                {
                    $arguments = array();
                    if($m["params"])
                    {
                        $params = explode(",", $m["params"]);
                        preg_match_all("#(?<arguments>%\w+)#", $m["source"], $mParams);
                        if($mParams && $mParams["arguments"])
                        {
                            for($i = 0; $i < count($mParams["arguments"]); $i++)
                            {
                                $arguments[$mParams["arguments"][$i]] = $params[$i];
                            }
                        }
                    }

                    return ezpI18n::tr($m["context"], $m["source"], null, $arguments);
                }
                return $text;
            },
            'taxonomies_filter' => function($text) use ($application) {
                $filterTaxonomies = $application->getCustomParameter('TaxonomiesFilter');

                $html = '';
                foreach($filterTaxonomies as $category)
                {
                    $taxonomies = FacetFilteringTool::getTaxonomyTranslationsByCategory($category);
                    $tpl = eZTemplate::factory();

                    $tpl->setVariable('taxonomies', $taxonomies);
                    $tpl->setVariable('category', $category);
                    $html .= $tpl->fetch( 'design:esibuild/app_content/channel/filter.tpl' );
                }
                return $html;
            },
            'editors_choice_content' => function($text) use ($application) {
                $taxonomyCategory = $application->getCustomParameter('EditorsChoiceFilter');
                $taxonomyValue = $application->getCustomParameter('EditorsChoiceValue');
                $limit = $application->getCustomParameter('EditorsChoiceLimit');
                $html = '';
                $language = eZINI::instance('site.ini')->variable('RegionalSettings', 'ContentObjectLocale');

                $fields = array(
                    'node_id'              => 'meta_node_id_si',
                    'object_id'            => 'meta_id_si',
                    'language'             => 'meta_language_code_ms',
                    'url'                  => 'attr_'.ClusterTool::clusterIdentifier().'_url_s',
                    'headline'             => 'attr_headline_s',
                    'promo_description'    => 'attr_promo_description_t',
                    'rating'               => 'attr_content_rating_'.ClusterTool::clusterIdentifier().'_f',
                    'views'                => 'attr_view_counter_'.ClusterTool::clusterIdentifier().'_i',
                    'app_identifiers'      => 'subattr_parent_application___identifier____s',
                    'apps'                 => 'subattr_local_application___source_mixed____s',
                    'app_id'               => 'subattr_local_application___source_id____s',
                    'online_date'          => 'attr_online_date_dt',
                    'score'                => 'score',
                    'publisher_path'       => 'subattr_publisher_folder___source_id____s',
                    'has_image'            => 'attr_has_image_'.ClusterTool::clusterIdentifier().'_bst',
                    'media_types'          => 'attr_media_content_types_'.ClusterTool::clusterIdentifier().'_bst',
                    'internal_id'          => 'attr_publisher_internal_id_s',
                    'link_url'             => 'attr_media_content_link_'.ClusterTool::clusterIdentifier().'____ms'
                );
                $filters = array(
                    "subattr_{$taxonomyCategory[0]}___source_id____s: \"{$taxonomyValue[0]}\"",
                    "meta_language_code_ms: \"{$language}\""
                );
                    
                $params = array(
                    'indent'        => 'on',
                    'q'             => '*:*',
                    'fq'            => implode(' AND ' , $filters),
                    'start'         => '0',
                    'rows'          => $limit,
                    'fl'            => implode(',',$fields),
                    'qt'            => 'ezpublish',
                    'explainOther'  => '',
                    'hl.fl'         => '',
                    'sort'          => "attr_online_date_dt desc",
                );
                
                $result = SolrTool::rawSearch($params);
                foreach ($result[response][docs] as $key => $value) {
                    
                    $result[response][docs][$key]['headline'] = $value['attr_headline_s'];
                    $result[response][docs][$key]['node_id'] = $value['meta_node_id_si'];
                    $result[response][docs][$key]['object_id'] = $value['meta_id_si'];
                    $result[response][docs][$key]['language'] = $value['meta_language_code_ms'];
                    $result[response][docs][$key]['promo_description'] = $value['attr_promo_description_t'];
                    
                    $app = CacheApplicationTool::buildLocalizedApplicationByApplication( $value['subattr_local_application___source_id____s'][0] );
                    $applicationObject = $app->applicationObject();
                    $applicationType   = $applicationObject->applicationType()->attribute('type_identifier');
                    $result[response][docs][$key]['application_name'] = $app->attribute('url_alias');
                    
                    $publisherPath = $value['subattr_publisher_folder___source_id____s'][0];
                    $publisher = PublisherFolder::getPublisherFromPath($publisherPath);
                    $publisherFolderId = $publisher->getTranslation()->attribute('publisher_folder_id');
                    $publisherName = $publisher->getTranslation()->attribute('name');
                    $result[response][docs][$key]['publisher_name'] = $publisherName;
                                  
                    $url = $value['attr_'.ClusterTool::clusterIdentifier().'_url_s'];
                    $url = ($applicationType == 'first-child')
                        ? $app->attribute('url_alias')
                        : $app->attribute('url_alias') . '/' . $publisherFolderId . '/' . $url;
                    $result[response][docs][$key]['url'] = $url;
                    $result[response][docs][$key]['online_date'] = solrTool::getDateFromSolr($value['attr_online_date_dt']);
                    $result[response][docs][$key]['publisher_name'] = $publisherName;
                    
                    $result[response][docs][$key]['has_image'] = json_decode( base64_decode($value['attr_has_image_'.ClusterTool::clusterIdentifier().'_bst']), true );
                    $mediaCase = ImageArticleTool::NEWS_APPLICATION_CASE;
                    $hasImage = $result[response][docs][$key]['has_image'][$mediaCase];
                    if ($hasImage) {
                        $result[response][docs][$key]["dt_url"] = SolrSafeOperatorHelper::getImageArticleUrl($mediaCase, $result[response][docs][$key]['object_id'], $result[response][docs][$key]['language'], 'dt_full');
                        $result[response][docs][$key]["mb_url"] = SolrSafeOperatorHelper::getImageArticleUrl($mediaCase, $result[response][docs][$key]['object_id'], $result[response][docs][$key]['language'], 'm_full');
                    }

                }
                
                $tpl = eZTemplate::factory();
                $tpl->setVariable('editorsChoice', $result);
                $html .= $tpl->fetch( 'design:esibuild/app_content/channel/editors_choice.tpl' );
                
                return $html;
            }
        );
    }
    /**
     * @return string
     */
    protected function startCourseOverWsdl()
    {
        $courseId    = ( isset( $_POST['courseid'] ) && filter_var($_POST['courseid'], FILTER_VALIDATE_REGEXP, SecurityTool::$ELEARNING_COURSEID_REGEXP) ) ? $_POST['courseid'] : null;
        
        $soapUrl            = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'WsdlUrl');
        $credentialLogin    = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'WsdlLogin');
        $credentialPassword = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'WsdlPassword');
        $useLocale          = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'UseLocale');
        $locale             = SolrSafeOperatorHelper::feature('OnlineVortrageSettings', 'Locale');
        
        $credentials = array(
            'login'    => $credentialLogin,
            'password' => $credentialPassword,
        );
        
        $params = array(
            array(
                'username' => MMUsers::getCurrentUserId(),
                'courseID' => $courseId,
            )
        );
        
        if ( $useLocale )
        {
            $params[0]['locale'] = $locale;
        }
        
        try
        {
            $soap   = new SoapClientAuth( $soapUrl, $credentials );
            $result = $soap->__soapCall( 'UnivadisEncrypt', $params );
            
            if ( isset($result) && isset($result->return) )
            {
                $url = $result->return;
                if ( strpos($url, 'http') !== 0 || strpos($url, 'https') !== 0)
                {
                    $url = 'http://' . $url;
                }
                
                if ( !ContextTool::instance()->isMobile() )
                {
                    $url = urlencode( urlencode( $url ) );
                    $url = '/external/deeplink?deeplink=' . $url . '&exit_strategy=0';
                }
                
                return $url;
            }
        }
        catch ( SoapFault $f )
        {
        }

        return false;
    }
    /**
     * @param string $url
     * @return array
     */
    public static function buildExitUrl( $url )
    {
        $infosApp = SolrSafeOperatorHelper::getInfosApp(ApplicationObject::EXIT_APPLICATION_IDENTIFIER);
        /* @type $application ApplicationObject */
        $application = $infosApp['application'];
        $externalConfiguration = $application->configurationExternal;

        //desktop external configuration values
        $externalConfigurationValues = array(1, 3);

        //mobile external configuration values
        if (ContextTool::instance()->isMobile())
            $externalConfigurationValues = array(2, 3);


        $displayIframe = in_array($externalConfiguration->attribute('display_iframe'), $externalConfigurationValues);
        $exitStrategy = in_array($externalConfiguration->attribute('exit_strategy'), $externalConfigurationValues);
        $newWindow = in_array($externalConfiguration->attribute('new_window'), $externalConfigurationValues);

        $result = array(
            'r' => $url,
            'display_iframe' => intval($displayIframe),
            'exit_strategy' => intval($exitStrategy),
            'new_window' => intval($newWindow),
        );

        $queryString = http_build_query($result);
        $result['url'] = $queryString;

        return $result;
    }
    /**
     * @param bool $forAnonmyous
     * @param null $processedUserCustomerType
     * @return int[]
     */
    public static function fetchAuthorizedApplicationIds( $forAnonmyous = false, $processedUserCustomerType = null )
    {
        if( !$forAnonmyous && !is_null(self::$_authorizedApplications) )
            return self::$_authorizedApplications;
        $db = MMDB::instance();

        $customerType   = null;
        $mainSpeciality = null;

        $whereString = sprintf(
            "     cluster_identifier='%s' 
              AND environment & %d",
            $db->escapeString(ClusterTool::clusterIdentifier()),
            ContextTool::instance()->environment()
        );
        
        $user = $forAnonmyous ? false : MMUsers::getCurrentUserObject();

        if( $user )
        {
            /* @var $user MMUsers */
            $user = MMUsers::getCurrentUserObject();

            $customerType   = $user->attribute('customer_type');
            $mainSpeciality = $user->attribute('main_speciality');

            if( $user->hasAttribute('prefered_language'))
            {
                $language = $user->attribute('prefered_language');

                $whereString.= sprintf(
                    " AND ( language = '%s' OR language IS NULL OR language = '0' )",
                    $db->escapeString($language)
                );
            }

            if( $user->hasAttribute('country'))
            {
                $country = $user->attribute('country');

                $whereString.= sprintf(
                    " AND ( country = '%s' OR country IS NULL OR country = '0' )",
                    $db->escapeString($country)
                );
            }
        }

        if (!$customerType && $processedUserCustomerType) {
            $customerType = $processedUserCustomerType;
        }
        $whereString .= is_null($customerType)
            ? ' AND customer_type IS NULL '
            : sprintf( " AND ( customer_type IS NULL OR customer_type = '0' OR customer_type='%s') ", $db->escapeString($customerType) );
        $whereString .= is_null($mainSpeciality)
            ? ' AND main_speciality IS NULL '
            : sprintf( " AND ( main_speciality IS NULL OR main_speciality = '0' OR main_speciality='%s') ", $db->escapeString($mainSpeciality) );

        $sql = "SELECT *
            FROM mm_country_application_library
            WHERE
            ".$whereString."
            ORDER BY country DESC, language DESC, customer_type DESC, main_speciality DESC";

        $lastProfile    = null;
        $excludedApps   = array();
        $applicationIds = array();

        foreach( $db->arrayQuery($sql) as $row )
        {
            $profile = serialize( array($row['customer_type'], $row['main_speciality']) );
            if( !is_null($lastProfile) && $profile != $lastProfile )
                break;

            $lastProfile = $profile;

            if( $user && $user->hasAttribute('state') && !is_null($user->attribute('state')) && $row['state'] === $user->attribute('state') )
            {
                $excludedApps[] = (int)$row['application_id'];
                continue;
            }

            $applicationIds[] = (int) $row['application_id'];
        }

        if( !empty($excludedApps) )
        {
            foreach ( $applicationIds as $k => $appId )
            {
                if( in_array($appId, $excludedApps ) )
                    unset( $applicationIds[$k] );
            }
            $applicationIds = array_values($applicationIds);
        }
        
        if(SolrSafeOperatorHelper::featureIsActive('LearningNeedsAssessment'))
        {
            $applicationIds[] = ApplicationObject::fetchByIdentifier('learning-needs-assessment')->attribute('id');
        }

        $applicationIds = array_unique( $applicationIds );

        if( !$forAnonmyous )
            self::$_authorizedApplications = $applicationIds;

        return $applicationIds;
    }
    /**
     * @param array $solrResult
     * @return array
     */
    public function facetResult( &$solrResult )
    {
        $translations = FacetFilteringTool::getTaxonomyTranslation ( $this->attribute );
        $result       = parent::facetResult($solrResult);

        //sorting
        $keysById = array();

        foreach ( $result as $k => $f )
            $keysById[$f['id']] = $k;

        $sortedResult = array();

        foreach($this->defaultValues as $id)
        {
            if( isset($keysById[$id]))
            {
                $visible = true;
                if (SolrSafeOperatorHelper::featureIsActive('Univadis18Redesign'))
                {
                    $hiddenValues = SolrSafeOperatorHelper::feature('Univadis18Redesign', 'SpecialtyFacetHiddenValues');
                    if (in_array($id, $hiddenValues)) {
                        $visible = false;
                    }
                }
                $f                              = $result[$keysById[$id]];
                $f['visible'] = $visible;
                $sortedResult[$keysById[$id]]   = $f;

            }
            else
            {
                if ( isset($translations[$id]) )
                {
                    $visible = true;
                    if (SolrSafeOperatorHelper::featureIsActive('Univadis18Redesign'))
                    {
                        $hiddenValues = SolrSafeOperatorHelper::feature('Univadis18Redesign', 'SpecialtyFacetHiddenValues');
                        if (in_array($id, $hiddenValues)) {
                            $visible = false;
                        }
                    }
                    $sortedResult[$translations[$id]] = array(
                        'count'    => 0,
                        'id'       => $id,
                        'checked'  => 0,
                        'visible' => $visible,
                    );
                }
            }
        }

        return $sortedResult;
    }
    }
    
    if( $value )
        setcookie( substr($value, -2) . '_Login', $value, 0, '/', CookieTool::getCookieDomain() );
    
}

$userId = MMUsers::getCurrentUserId();
if ( !MMUsers::isAnonymous($userId) )
{
    if ( SolrSafeOperatorHelper::featureIsActive( 'ToUPPPopin' ) )
    {
        if (
            ( !ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPage' ) )
            ||
            ( ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature('ToUPPPopin','showOnMobile') && SolrSafeOperatorHelper::feature('ToUPPPopin','useDedicatedPageMobile') )
        )
        {
            $serviceLogin = ESBFactory::getLoginService( ServiceLoginBase::ESB_METHOD_AUTOLOGIN, $_REQUEST );
            if ( $serviceLogin->checkTouPPPopin( ESBFactory::getUserService()->form() ) )
            {
                CookieTool::destroyCookie( 'displayToUPPPopin' );
                CookieTool::destroyCookie( 'displayToUPPPopin', '/', null );
                $serviceLogin->login();
                eZExecution::cleanExit();
            }
        }
    }

    // User is already logged-in, we redirect him
    $context = isset( $_REQUEST['context'] ) ? $_REQUEST['context'] : false;
    /**
     * @param string$clusterIdentifier
     * @param bool $backupExisting
     * @param bool $includeTimestamp
     * @return array
     * @throws Exception
     */
    public function generateSpriteForCluster($clusterIdentifier, $backupExisting = true, $includeTimestamp = true)
    {
        $outputFile = $this->buildFilePath($this->outputPath, array($clusterIdentifier));
        $timestampOutputFile = $this->generateFileName($outputFile, $includeTimestamp);
        $generatedSpriteName = substr($timestampOutputFile, strrpos($timestampOutputFile, '/') + 1);

        ClusterTool::setCurrentCluster( $clusterIdentifier );

        $lessPath = "extension/{$clusterIdentifier}/design/oscar/stylesheets/";
        $icoSprite = "/ico_sprite.png";
        $offsetStep = 95;
        $crop = $offsetStep * 2;
        $mobileStep = 83;
        $spriteConvertOptions = " -crop x{$crop}+0+0 ";
        $globalConvertOptions = " -append -quality 80%";

        $applicationList = CacheApplicationTool::clusterApplications();
        $cssList = array();
        $icoList = array();
        foreach( $applicationList as $application )
        {
            $icoCss = 'ico_'.SolrSafeOperatorHelper::getAppIdentifierForIcon( $application->applicationObject->identifier );
            $icoFile = StaticData::clusterFilePath( $clusterIdentifier, 'apps/'.$application->applicationObject->identifier.$icoSprite, true, true );

            if ( ! file_exists( $icoFile ) )
            {
                $icoFile = StaticData::clusterFilePath( 'default', 'apps/'.$application->applicationObject->identifier.$icoSprite, true, true );
            }
            if ( file_exists( $icoFile ) && ! in_array( $icoCss, $cssList ) )
            {
                $cssList[] = $icoCss;
                $icoList[] = $icoFile;
            }
        }

        if (empty($icoList))
        {
            throw new \Exception("No icons found for cluster {$clusterIdentifier}", 0);
        }
        if ($backupExisting && file_exists($outputFile))
        {
            rename($outputFile, $outputFile . '.bak');
        }
        $convertBinPath = $this->convertBinPath;

        $cmd = 'export PATH=$PATH:' . $convertBinPath . '; convert ' . implode( $spriteConvertOptions, $icoList ) . "{$spriteConvertOptions} {$globalConvertOptions} {$outputFile}";
        $cmdStatus = 0;
        $cmdOutput = array();
        exec($cmd, $cmdOutput, $cmdStatus);
        if ($cmdStatus != 0)
        {
            return array(
                'errorCode' => $cmdStatus,
                'generateSpriteCommand' => $cmd,
                'error' => implode('\n', $cmdOutput),
            );
        }

        $css = "
#app-catalog a.app-bar-access-app-library .poster{
    background-image: none !important;
}
#app-catalog a .poster,
#hide-app a .poster,
.item-apps .batch .wrap > a .poster,
.item-related-app .batch .wrap > a .poster{
      background-image:url(/esibuild/static/{$clusterIdentifier}/{$generatedSpriteName});
      background-repeat: no-repeat;
}
";
        $cssMobile = "
#app-catalog a.app-bar-access-app-library .poster{
    background-image: none !important;
}
#app-catalog a .poster,
#hide-app a .poster,
.item-apps .batch .wrap > a .poster,
.item-related-app .batch .wrap > a .poster{
      background-image:url(/esibuild/static/{$clusterIdentifier}/{$generatedSpriteName});
      background-repeat: no-repeat;
      background-size: {$mobileStep}px auto !important;
}
";
        $offset = 0;
        $offsetMobile = 0;
        foreach( $cssList as $key => $cssStyle )
        {
            $css .= "
#app-catalog a .poster.$cssStyle,
#hide-app a .poster.$cssStyle,
.item-apps .batch .wrap > a .poster.$cssStyle,
.item-related-app .batch .wrap > a .poster.$cssStyle{
      background-position: 0 -{$offset}px !important;
}
";
            $cssMobile .= "
#app-catalog a .poster.$cssStyle,
#hide-app a .poster.$cssStyle,
.item-apps .batch .wrap > a .poster.$cssStyle{
      background-position: 0 -{$offsetMobile}px !important;
}
";
            $offset += $offsetStep;
            $offsetMobile += $mobileStep;
            $css .= "
#app-catalog a:hover .poster.$cssStyle,
#app-catalog a:active .poster.$cssStyle,
#app-catalog a.active .poster.$cssStyle,
#hide-app a:active .poster.$cssStyle,
#hide-app a.active .poster.$cssStyle,
.item-apps .batch:hover .wrap > a .poster.$cssStyle,
.item-related-app .batch:hover .wrap > a .poster.$cssStyle{
      background-position: 0 -{$offset}px !important;
}
";
            $cssMobile .= "
#app-catalog a:hover .poster.$cssStyle,
#app-catalog a:active .poster.$cssStyle,
#app-catalog a.active .poster.$cssStyle,
#hide-app a:active .poster.$cssStyle,
#hide-app a.active .poster.$cssStyle,
.item-apps .batch:hover .wrap > a .poster.$cssStyle,
.item-related-app .batch:hover .wrap > a .poster.$cssStyle{
      background-position: 0 -{$offsetMobile}px !important;
}
";
            $offset += $offsetStep;
            $offsetMobile += $mobileStep;
        }

        if ( ! file_exists( $lessPath ) )
        {
            mkdir( $lessPath, 0755 );
        }
        if ( is_dir( $lessPath ) )
        {
            $lessFile = $lessPath."mod.icosprite.less";
            file_put_contents( $lessFile, $css );
            $lessFileMobile = $lessPath."mod.icosprite.mobile.less";
            file_put_contents( $lessFileMobile, $cssMobile );
            eZCache::clearByID( array('ezjscore-packer'), 'template-block' );
        }

        return array(
            'errorCode' => 0,
            'generateSpriteCommand' => $cmd
        );
    }
    /**
     * This function construct different parameter for an article for template mustache
     * @param $articles
     * @param $additionalMappingTaxonomies
     * @param ChannelBlock $block
     * @return array
     */
    private function constructArticles($articles, $additionalMappingTaxonomies, ChannelBlock $block)
    {
        $taxonomyTranslations = $constructedArticles = array();
        foreach($articles as $article)
        {
            // add view parameter channel in url
            $article["url"] .= "/(channel)/".$block->attribute("id");

            // info for sorting articles cross applications
            $article["info_sort"] = array();

            if($article["online_date"])
            {
                $article["info_sort"]["date"] = solrTool::getTimestampFromSolr($article["online_date"]);
                $article["online_date"]       = solrTool::getDateFromSolr($article["online_date"]);
            }

            $article["info_sort"]["rating"]   = $article["rating"];
            $article["info_sort"]["views"]    = $article["views"];
            $article["info_sort"]["headline"] = $article["headline"];
            $article["info_sort"]["score"]    = $article["score"];

            $mediaCase = ImageArticleTool::MULTIMEDIA_APPLICATION_CASE;
            $hasImage = SolrSafeOperatorHelper::hasImageArticleFromSolr($article, $mediaCase);
            if( !$hasImage )
            {
                $mediaCase = ImageArticleTool::NEWS_APPLICATION_CASE;
                $hasImage = SolrSafeOperatorHelper::hasImageArticleFromSolr($article, $mediaCase);
            }

            // image information
            $article["hasDtImage"] = $hasImage;
            $article["hasMbImage"] = $hasImage;

            if ( $hasImage )
            {
                $article["dt_url"] = SolrSafeOperatorHelper::getImageArticleUrl($mediaCase, $article['object_id'], $article['language'], 'dt_full');
                $article["mb_url"] = SolrSafeOperatorHelper::getImageArticleUrl($mediaCase, $article['object_id'], $article['language'], 'm_full');
            }

            $promoTaxonomy = $this->getCustomParameter('PromoTaxonomy');

            foreach ($article['media_types'] as $type => $value)
            {
                $article["has_media_{$type}"] = true;
            }

            $article['hasPromoTaxonomy'] = false;

            // construct taxonomies fields
            foreach($additionalMappingTaxonomies as $taxonomyCategory => $solrField)
            {
                if ($taxonomyCategory == $promoTaxonomy)
                {
                    if (count($article[$taxonomyCategory]) == 1 && $article[$taxonomyCategory][0] != '')
                    {
                        $article['hasPromoTaxonomy'] = true;
                        $article['promoTaxonomy'] = FacetFilteringTool::getTaxonomyTranslationByCode($article[$taxonomyCategory][0]);
                    }
                }
                // special case for retrieve value of taxonomy publisher folder
                if($taxonomyCategory == "publisher_folder")
                {
                    $publisher = PublisherFolder::getPublisherFromPath($article["publisher_folder"][0]);
                    if($publisher)
                    {
                        $article["publisher_folder"] = $publisher->getTranslation()->attribute("name");
                    }
                    else
                    {
                        $article["publisher_folder"] = null;
                    }
                }
                else
                {
                    if(!empty($article[$taxonomyCategory]) && $article[$taxonomyCategory][0] != "")
                    {
                        if(empty($taxonomyTranslations[$taxonomyCategory]))
                        {
                            $taxonomyTranslations[$taxonomyCategory] = FacetFilteringTool::getTaxonomyTranslation($taxonomyCategory);
                        }

                        $article[$taxonomyCategory] = $taxonomyTranslations[$taxonomyCategory][$article[$taxonomyCategory][0]];
                    }
                    else
                    {
                        // if the category has not value, we remove the entry in article
                        unset($article[$taxonomyCategory]);
                    }
                }
            }

            $this->constructAdditionalInformations($article);
            // rebuild array for delete keys for mustache
            $constructedArticles[] = $article;
        }

        return $constructedArticles;
    }
<?php

return array(
    'name' => 'Univadis',
    'apiVersion' => 0.3,
    'baseUrl' => (\SolrSafeOperatorHelper::featureIsActive('UUMP') ? \SolrSafeOperatorHelper::clusterIni('WebService', 'BaseUrlUUMP', 'merck.ini') . \SolrSafeOperatorHelper::clusterIni('WebService', 'Prefix', 'merck.ini') : \SolrSafeOperatorHelper::clusterIni('WebService', 'BaseUrl', 'merck.ini')),
    'description' => 'RESTful Webservice for ESB',
    'operations' => array(
        'abstract' => array(
            'httpMethod' => 'POST'
        ),
        'createtoken' => array(
            'extends' => 'abstract',
            'uri' => '/createtoken',
            'summary' => 'Creates token for given username',
            'parameters' => array(
                'data' => array(
                    'email' => 'string',
                    'countryOfRegistration' => 'string'
                )
            )
        )
    )
);
    /**
     * @return bool
     */
    public static function isCatchUpAppNameEnabled()
    {
        $isFeatureActive  = SolrSafeOperatorHelper::featureIsActive( 'GlobalSearch' );
        $isFeatureEnabled = SolrSafeOperatorHelper::feature( 'GlobalSearch', 'CatchAppNameEnabled' );

        return $isFeatureActive && $isFeatureEnabled;
    }
    'cluster' => 'Cluster'
) );

$script->startup();
$script->initialize();

if(!isset($options['cluster']) || empty($options['cluster']) || is_null($options['cluster'])) {
    echo "\nError : Cluster must be set, consult help for more informations\n";
    $script->shutdown();
    exit;
}

if(isset($options['cluster']) && !empty($options['cluster'])) {
    generateCache(array($options['cluster']), $options);
} else {
    $clusters = array_keys( SolrSafeOperatorHelper::clusterIni('DomainMappingSettings', 'ClusterDomains', 'merck.ini') );
    generateCache($clusters, $options);
}

$script->shutdown();

/**
 * @param $clusters
 * @param $options
 * @return void
 */
function generateCache($clusters, $options) {
    $cli = eZCLI::instance();

    foreach ( $clusters as $clusterPath )
    {
    /**
     * @return bool
     */
    public function jsonBuildResult()
    {
        $this->initChannelInformations();

        $editorsChoice = $this->getEditorsChoice();

        $this->resultHandler->parseRequestParams(true);
        $solrResult = $this->resultHandler->contentResultMain();
        if ($this->getCustomParameter('IncludeChildrenInSearch'))
        {
            $this->resultHandler->getChildArticles($solrResult);
        }

        $facets     = array();

        $this->pushResult('num_found', (int)$solrResult['response']['numFound']);
        $this->pushResult('with_feed', $this->resultHandler->withFeed);

        if ( $this->resultHandler->withFacets )
        {
            foreach ( $this->facets as $facet)
            {
                /* @var $facet FacetBase */
                $f = array(
                    'uxtype'    => $facet->uxtype,
                    'list'      => ( $facet->isFiltered() ) ? $this->resultHandler->filteredFacetResult( $facet  ) : $facet->facetResult( $solrResult )
                );

                // JsonBuildResult is called again with facet with no result unchecked (state change via $this->facets)
                if ( $facet->needsRefresh )
                    return $this->jsonBuildResult();

                $facets[$facet->key] = $f;
            }

            $this->pushResult('facets', $facets);
        }

        if (!empty($editorsChoice))
        {
            $editorsChoice = $this->resultHandler->articleResult($editorsChoice, $facets);
            $this->pushResult('editors_choice' , $this->getEditorsChoiceView($editorsChoice));
        }


        $solrReturn = $this->resultHandler->articleResult($solrResult, $facets);

        $this->pushResult('articles', $this->setVariableAndGetTpl($solrReturn));
        if ( isset($solrReturn['all_specialities_informations'] ) )
        {
            $allSpecialitiesInformations = $solrReturn['all_specialities_informations'];
            unset( $solrReturn['all_specialities_informations'] );
            if (SolrSafeOperatorHelper::featureIsActive('SpecialityPopin') && SolrSafeOperatorHelper::feature('SpecialityPopin', 'CustomGroupsEnabled')) {
                $flatSpecialitiesList = array();
                foreach($allSpecialitiesInformations['all_specialities'] as $value) {
                    foreach($value as $name => $data) {
                        $name = StringTool::trim($name);
                        $flatSpecialitiesList[$name] = $data;
                    }
                }

                $customGroups = SolrSafeOperatorHelper::feature('SpecialityPopin', 'Groups');
                $allSpecialities = array();

                foreach ($customGroups as $name => $specialities) {
                    $name = StringTool::trim($name);
                    $allSpecialities[$name] = array();
                    foreach($specialities as $speciality) {
                        $speciality = StringTool::trim($speciality);
                        if (isset($flatSpecialitiesList[$speciality])) {
                            $allSpecialities[$name][$speciality] = $flatSpecialitiesList[$speciality];
                            unset($flatSpecialitiesList[$speciality]);
                        }
                    }
                }

                $allSpecialitiesInformations['all_specialities'] = $allSpecialities;
            }

            foreach ($allSpecialitiesInformations as $templateVariable => $templateValue)
                $this->tpl()->setVariable($templateVariable, $templateValue);

            $this->pushResult('all_specialities', $this->tpl()->fetch('design:'.$this->templateRootDirectory().'/content_service/specialities_list.tpl'));
        }
        
        $t3Facet = array();
        
        if ( isset($solrReturn['t3_facet_informations'] ) )
        {
            if ( count($solrReturn['t3_facet_informations']) > 0 )
            {
                $t3FacetInformations = $solrReturn['t3_facet_informations'];

                foreach ($t3FacetInformations as $templateVariable => $templateValue)
                    $this->tpl()->setVariable($templateVariable, $templateValue);

                $t3Facet[$t3FacetInformations['t3_key']] = $this->tpl()->fetch('design:'.$this->templateRootDirectory().'/content_service/t3_facet_list.tpl');

            }
            unset( $solrReturn['t3_facet_informations'] );
        }
        $this->pushResult('t3_facets', $t3Facet);
        
        foreach ( $solrReturn as $resultVariable => $resultValue )
            $this->pushResult($resultVariable, $resultValue);

        return true;
    }