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 ) );
                }
            }
        }
    }
    public static function getPublisherArticleUrl($publisher, $articleId)
    {
        $fields = array(
            'apps' => 'subattr_local_application___source_mixed____s',
            'url'  => 'attr_'.ClusterTool::clusterIdentifier().'_url_s',
            'publisher_path' => 'subattr_publisher_folder___source_id____s',
        );

        $fq = array(
            "subattr_publisher_folder___source_id____s: \"{$publisher}\"",
            "attr_publisher_internal_id_s: \"{$articleId}\"",
        );

        $params = array(
            'indent'        => 'on',
            'q'             => '',
            'start'         => 0,
            'rows'          => 1,
            'fq'            => implode(' AND ', $fq),
            'fl'            => implode(',', array_values($fields)),
            'qt'            => 'ezpublish',
            'explainOther'  => '',
            'hl.fl'         => '',
        );

        $raw = SolrTool::rawSearch($params);
        if ($raw['response']['numFound'] == 0)
        {
            return null;
        }
        $row = $raw['response']['docs'][0];

        $solrApplicationIndexes = $row[$fields['apps']];
        $solrApplicationIdentifiers = array();
        $solrApplicationNames = array();

        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');
            }
        }

        if (empty($solrApplicationIdentifiers))
        {
            return;
        }
        $applicationIdentifier = $solrApplicationIdentifiers[0];
        $application = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );
        $applicationObject = $application->applicationObject();
        $applicationType = $applicationObject->applicationType()->attribute('type_identifier');
        $publisherPath = $row[$fields['publisher_path']][0];
        $publisherInfo = PublisherFolderTool::getPathToIDMapping($publisherPath);
        $publisherFolderId = $publisherInfo['pfid'];

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

        $url = ($applicationType == 'first-child')
            ? $application->attribute('url_alias')
            : $application->attribute('url_alias') . '/' . $publisherFolderId . '/' . $url;

        return $url;
    }
    /**
     * @param bool $withRootNodeFilters
     * @return string
     */
    public function getPublishersFilter( $withRootNodeFilters = true )
    {
        if ( !is_array($this->publisherFolders) || count($this->publisherFolders) == 0 )
            return false;

        $publisherFilters  = array();

        foreach ( $this->publisherFolders as $publisherFolder )
        {
            $publisherFilter = $this->publisherFolderFilter( $publisherFolder );

            if ( $publisherFilter !== false )
                $publisherFilters[] = $publisherFilter;
        }

        if( !empty( $publisherFilters ) && $withRootNodeFilters )
        {
            $pfPathToIDMapping = PublisherFolderTool::getPathToIDMapping();
            $ids               = array();

            foreach( $this->publisherFolders as $path => $publisherFolder )
                $ids[] = $pfPathToIDMapping[$path]['nid'];

            return 'meta_path_si:('.implode( ' OR ', $ids ).') AND ( '.implode( ' OR ', $publisherFilters ).' )';
        }
        elseif ( !empty( $publisherFilters ) )
        {
            return '( '.implode( ' OR ', $publisherFilters ).' )';
        }

        return false;
    }
    /**
     * @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' )
                )
            );
        }
    }
    /**
     * recursively get children for a specific parent path
     *
     * @param array $articles
     * @param string $parentPath
     * @return array
     */
    private function getChildren($articles, $parentPath)
    {
        $result = array();

        foreach($articles as $article)
        {
            if($parentPath.$article["meta_main_node_id_si"]."/" == $article["main_node_meta_path_string_ms"])
            {
                $publisherPath     = $article['subattr_publisher_folder___source_id____s'][0];
                $publisherInfo     = PublisherFolderTool::getPathToIDMapping($publisherPath);
                $publisherFolderId = $publisherInfo['pfid'];

                $result[] = array(
                    "title" => $article["attr_headline_s"],
                    "children" => $this->getChildren($articles, $article["main_node_meta_path_string_ms"]),
                    "url" => sprintf(
                        '%s/%s/%s',
                        $this->_application->applicationLocalized()->applicationUrl(),
                        $publisherFolderId,
                        $article["attr_".ClusterTool::clusterIdentifier()."_url_s"]
                    ),
                );
            }
        }

        return $result;
    }
    /**
     * @param $appArticles
     * @param bool $subject
     * @param bool $debug
     * @return array
     */
    protected function constructTemplateAssocArray($appArticles, $subject = false, $debug = false, $supersubject = false, $clusterIdentifier)
    {
        //domains
        $domainsInClusters = eZINI::instance( 'merck.ini' )->variable( 'DomainMappingSettings', 'ClusterDomains' );
        $domain = $domainsInClusters[$clusterIdentifier];

        // Link
        $merckIni = eZINI::instance( 'merck.ini' );
        $urlAdditionalValues = $merckIni->variable( 'RssUrlSettings', 'AdditionalValues' );

        //application
        $applicationInfos = $this->getApplicationInfos($appArticles['applicationDictionaryRow']['application_id'], $clusterIdentifier);
        $applicationTitle = $applicationInfos['headline'];
        $applicationUrl = 'http://' . rtrim($domain, '/') . '/' . $applicationInfos['url'];
        $applicationImage = isset($appArticles['applicationDictionaryRow']['publisher_logo']) && !is_null($appArticles['applicationDictionaryRow']['publisher_logo']) ? $appArticles['applicationDictionaryRow']['publisher_logo'] : '';
        $applicationElementsNumber = $appArticles['applicationDictionaryRow']['number_article_ns'];
        $applicationTopArticlesNumber =  $appArticles['applicationDictionaryRow']['number_article_top'];


        $articles = $appArticles['articles'];

        $orderedListArticles = array();

        //topArticle
        $hasTopArticle = true;
        $hasTopArticles = false;
        $topArticleImage = false;

        //otherArticles
        $otherArticles = array();

        $elementCount = 0;
        $locale = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'exact_target' );

        foreach ( $articles as $article )
        {
            //publisher folder
            $publisherPath = $article['subattr_publisher_folder___source_id____s'][0];
            $publisherId   = PublisherFolderTool::getPathToIDMapping($publisherPath);

            if($applicationElementsNumber != -1)
            {
                if($elementCount >= $applicationElementsNumber)
                {
                    break;
                }
            }

            if(isset($article["is_sdk_b"]) && $article["is_sdk_b"])
            {
                $url = '/' . $applicationInfos['url'] . '/' . $article['meta_url_alias_ms'][0];
            }
            else
            {
                $url = '/' . $applicationInfos['url'] . '/' . $publisherId['pfid'] . '/' . $article['attr_' . $clusterIdentifier . '_url_s'];
            }

            if ( isset( $urlAdditionalValues[$clusterIdentifier] ) )
            {
                $linkUrl = 'http://' . rtrim($domain, '/') . '/' . $urlAdditionalValues[$clusterIdentifier] . $url;
            }
            else
            {
                $linkUrl = 'http://' . rtrim($domain, '/') . $url;
            }

            $image = null;
            $hasImageArray = json_decode( base64_decode($article['attr_has_image_' . $clusterIdentifier . '_bst']) );
            $publishDate = DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $article["attr_online_date_dt"])->format('Y-m-d H:i:s');
            $isEmptyHeadline = trim($article['attr_promo_headline_t']) == "";

            if ( SolrSafeOperatorHelper::hasImageArticleFromSolr( array( 'has_image' => $hasImageArray ), 1) )
            {
                $image = SolrSafeOperatorHelper::getImageArticleUrl(1, $article['meta_id_si'], $article['meta_language_code_ms'], 'm_mosaic');
                $image = 'http://' . rtrim($domain, '/') . $image;
            }

            if(!is_null($article['attr_featured_content_b']) && $article['attr_featured_content_b'] == true)
            {
                $hasTopArticle = true;
                $topArticleImage = false;

                if($image)
                {
                    //$topArticleImage = $this->getImageFromArticleNodeId($image);
                    $topArticleImage = $image;
                }

                //top top articles
                if( !$isEmptyHeadline )
                {
                    $title = $article['attr_headline_s'];
                    if ($subject)
                    {
                        $title = '';
                        if ($this->getRssType() != 'oncology' )
                        {
                            $title = $article['attr_headline_s'];
                        }
                        if (!$isEmptyHeadline) {
                            $title = $article['attr_promo_headline_t'];
                        }
                    }



                    $xmlTitle = $this->escapeStr( $title );

                    if($clusterIdentifier == 'cluster_pt')
                    {
                        $xmlTitle = $this->escapeStr( $article['attr_promo_headline_t']);
                    }


                    $expirationDate = null;
                    if(isset($article['subattr_download_ressource___expiration_date____dt']))
                    {
                        $i=0;
                        foreach($article['subattr_download_ressource___expiration_date____dt'] as $exDate){
                            $expirationDate_tmp[$i] = DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $exDate)->format('Y.m.d H:i');
                            $i++;
                        }
                            $expirationDate = max($expirationDate_tmp);
                    }
                    $orderedListArticles['toptop'][] = array (
                        'title'         => $xmlTitle,
                        'url'           => $this->buildUrl($linkUrl, $locale),
                        'description'   => $article['attr_promo_description_t'],
                        'source'        => $article['attr_source_t'],
                        'image'         => $topArticleImage ? $topArticleImage : '',
                        'publishDate'   => $publishDate,
                        'coreContent'   => $article['attr_core_content_t'],
                        'guid'          => $article['attr_node_remote_s'],
                        'expirationDate'    => $expirationDate,
                        'hasQuizReplies'    => ( isset($article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms']) && count($article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms']) > 0 ),
                        'quizReplies'       => $article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms'],
                        'hasQuizPoints' => isset($article['attr_media_content_quiz_points_' . ClusterTool::clusterIdentifier() . '_i']),
                        'quizPoints'    => $article['attr_media_content_quiz_points_' . ClusterTool::clusterIdentifier() . '_i'],
                        'hasQuizQuestion'   => isset($article['attr_media_content_quiz_question_' . ClusterTool::clusterIdentifier() . '_ms']),
                        'quizQuestion'      => $article['attr_media_content_quiz_question_' . ClusterTool::clusterIdentifier() . '_ms'],
                    );
                }
                //top articles
                else
                {
                    $title = $article['attr_headline_s'];
                    if ($subject)
                    {
                        $title = '';
                        if ($this->getRssType() != 'oncology' )
                        {
                            $title = $article['attr_headline_s'];
                        }
                        if (!$isEmptyHeadline) {
                            $title = $article['attr_promo_headline_t'];
                        }
                    }
                    $expirationDate = null;
                    if(isset($article['subattr_download_ressource___expiration_date____dt']))
                    {
                        $i=0;
                        foreach($article['subattr_download_ressource___expiration_date____dt'] as $exDate){
                            $expirationDate_tmp[$i] = DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $exDate)->format('Y.m.d H:i');
                            $i++;
                        }
                        $expirationDate = max($expirationDate_tmp);
                    }
                    $orderedListArticles['top'][] = array (
                        'title'         => $title,
                        'url'           => $this->buildUrl($linkUrl, $locale),
                        'description'   => $article['attr_promo_description_t'],
                        'source'        => $article['attr_source_t'],
                        'image'         => $topArticleImage ? $topArticleImage : '',
                        'publishDate'   => $publishDate,
                        'coreContent'   => $article['attr_core_content_t'],
                        'guid'          => $article['attr_node_remote_s'],
                        'expirationDate'    => $expirationDate,
                        'hasQuizReplies'    => ( isset($article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms']) && count($article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms']) > 0 ),
                        'quizReplies'       => $article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms'],
                        'hasQuizPoints' => isset($article['attr_media_content_quiz_points_' . ClusterTool::clusterIdentifier() . '_i']),
                        'quizPoints'    => $article['attr_media_content_quiz_points_' . ClusterTool::clusterIdentifier() . '_i'],
                        'hasQuizQuestion'   => isset($article['attr_media_content_quiz_question_' . ClusterTool::clusterIdentifier() . '_ms']),
                        'quizQuestion'      => $article['attr_media_content_quiz_question_' . ClusterTool::clusterIdentifier() . '_ms'],
                    );
                }
            }
            //otherArticles
            else
            {
                $title = $article['attr_headline_s'];
                if ($subject)
                {
                    $title = '';
                    if ($this->getRssType() != 'oncology' )
                    {
                        $title = $article['attr_headline_s'];
                    }
                    if (!$isEmptyHeadline) {
                        $title = $article['attr_promo_headline_t'];
                    }
                }
                $expirationDate = null;
                if(isset($article['subattr_download_ressource___expiration_date____dt']))
                {
                    $i=0;
                    foreach($article['subattr_download_ressource___expiration_date____dt'] as $exDate){
                        $expirationDate_tmp[$i] = DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $exDate)->format('Y.m.d H:i');
                        $i++;
                    }
                    $expirationDate = max($expirationDate_tmp);
                }

                $orderedListArticles['others'][] = array(
                    'title'             => $title,
                    'url'               => $this->buildUrl($linkUrl, $locale),
                    'description'       => $article['attr_promo_description_t'],
                    'source'        => $article['attr_source_t'],
                    'image'             => $image,
                    'isTop'             => false,
                    'publishDate'       => $publishDate,
                    'coreContent'       => $article['attr_core_content_t'],
                    'guid'              => $article['attr_node_remote_s'],
                    'expirationDate'    => $expirationDate,
                    'hasQuizReplies'    => ( isset($article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms']) && count($article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms']) > 0 ),
                    'quizReplies'       => $article['attr_media_content_quiz_replies_' . ClusterTool::clusterIdentifier() . '____ms'],
                    'hasQuizPoints' => isset($article['attr_media_content_quiz_points_' . ClusterTool::clusterIdentifier() . '_i']),
                    'quizPoints'    => $article['attr_media_content_quiz_points_' . ClusterTool::clusterIdentifier() . '_i'],
                    'hasQuizQuestion'   => isset($article['attr_media_content_quiz_question_' . ClusterTool::clusterIdentifier() . '_ms']),
                    'quizQuestion'      => $article['attr_media_content_quiz_question_' . ClusterTool::clusterIdentifier() . '_ms'],
                );
            }

            $elementCount++;
        }

        if($debug)
        {
            var_dump("ORDERED ", $appArticles["applicationDictionaryRow"]["id"], $orderedListArticles);
        }

        //get top article
        if($applicationTopArticlesNumber > 1){
            $hasTopArticles = true;
            for($i = 0; $i < $applicationTopArticlesNumber; $i++){
                if(count($orderedListArticles['toptop']) > 0)
                {
                    $topArticle = array_shift($orderedListArticles['toptop']);
                    
                    $topArticleImage = isset($topArticle['image']) ? $topArticle['image'] : null ;
                    $hasQuizReplies  = isset($topArticle['hasQuizResplies']) ? $topArticle['hasQuizReplies'] : false;
                    $quizReplies     = isset($topArticle['quizReplies']) ? $topArticle['quizReplies'] : null;
                    
                    $topArticles[] = $topArticle;
                }
                else if(count($orderedListArticles['top']) > 0)
                {
                    $topArticle = array_shift($orderedListArticles['top']);
                    
                    $topArticleImage = isset($topArticle['image']) ? $topArticle['image'] : null ;
                    $hasQuizReplies  = isset($topArticle['hasQuizReplies']) ? $topArticle['hasQuizReplies'] : false;
                    $quizReplies     = isset($topArticle['quizReplies']) ? $topArticle['quizReplies'] : null;
                    
                    $topArticles[] = $topArticle;
                }
                else if(count($orderedListArticles['others']) > 0)
                {
                    $topArticle = array_shift($orderedListArticles['others']);
                    
                    $topArticleImage = isset($topArticle['image']) ? $topArticle['image'] : null ;
                    $hasQuizReplies  = isset($topArticle['hasQuizReplies']) ? $topArticle['hasQuizResplies'] : false;
                    $quizReplies     = isset($topArticle['quizReplies']) ? $topArticle['quizReplies'] : null;
                    
                    $topArticles[] = $topArticle;
                }
            }
        }
        else if($applicationTopArticlesNumber == 1){
            if(count($orderedListArticles['toptop']) > 0)
            {
                $topArticle = array_shift($orderedListArticles['toptop']);
                $topArticleImage = isset($topArticle['image']) ? $topArticle['image'] : null ;
                $hasQuizReplies  = isset($topArticle['hasQuizReplies']) ? $topArticle['hasQuizReplies'] : false;
                $quizReplies     = isset($topArticle['quizReplies']) ? $topArticle['quizReplies'] : null;
            }
            else if(count($orderedListArticles['top']) > 0)
            {
                $topArticle = array_shift($orderedListArticles['top']);
                $topArticleImage = isset($topArticle['image']) ? $topArticle['image'] : null ;
                $hasQuizReplies  = isset($topArticle['hasQuizReplies']) ? $topArticle['hasQuizReplies'] : false;
                $quizReplies     = isset($topArticle['quizReplies']) ? $topArticle['quizReplies'] : null;
            }
            else if(count($orderedListArticles['others']) > 0)
            {
                $topArticle = array_shift($orderedListArticles['others']);
                $topArticleImage = isset($topArticle['image']) ? $topArticle['image'] : null ;
                $hasQuizReplies  = isset($topArticle['hasQuizReplies']) ? $topArticle['hasQuizReplies'] : false;
                $quizReplies     = isset($topArticle['quizReplies']) ? $topArticle['quizReplies'] : null;
            }
            $topArticles = array(
                $topArticle
            );
            $hasTopArticles = $topArticle != null;
        }
        
        //othersArticles
        if(count($orderedListArticles['toptop']) > 0)
        {
            $otherArticles = $orderedListArticles['toptop'];
        }

        if(count($orderedListArticles['top']) > 0)
        {
            $otherArticles = array_merge($otherArticles, $orderedListArticles['top']);
        }

        if(count($orderedListArticles['others']) > 0)
        {
            $otherArticles = array_merge($otherArticles, $orderedListArticles['others']);
        }

        return array(
            'applicationTitle'    => $applicationTitle,
            'applicationUrl'      => $this->buildUrl($applicationUrl, $locale),
            'applicationHasImage' => !empty($applicationImage),
            'applicationImage'    => $applicationImage,
            'hasOtherArticle'     => ( count($otherArticles) != 0 ),
            'otherArticles'       => $otherArticles,
            'hasOtherArticles'    => ( count($otherArticles) != 0 ),
            'topArticle'          => ( isset ($topArticle) ? $topArticle : null ),
            'topArticles'         => ( isset ($topArticles) ? $topArticles : null ),
            'topArticleHasImage'  => $topArticleImage,
            'hasTopArticle'       => $hasTopArticle,
            'hasTopArticles'      => $hasTopArticles,
            'hasQuizReplies'      => $hasQuizReplies,
            'quizReplies'         => $quizReplies,
            
        );
    }
    /**
     * 
     * @param string $nodePath
     * @param ApplicationDefault $app
     * @return null
     */
    static public function findNodeFromPath ($nodePath, $app )
    {
        $uri             = explode( '/', ltrim( $nodePath, '/' ) );
        $rootNodes       = array();
        $applicationName = $app->applicationName();

        if( count( $uri ) > 1 && is_numeric($uri[0]) )
        {
            $publisherFolderId = $uri[0];
            array_shift($uri);
            $uriArticle = implode ('/', $uri);
        }
        else
            $uriArticle = ltrim( $nodePath, '/' );
        
        $uriArticle = urldecode($uriArticle);

        if($applicationName)
        {
            $publishers = $app->applicationLocalized()->publisherFolders;

            /* @var $publisher PublisherFolder */
            foreach ($publishers as $publisher)
            {
                $pfids = PublisherFolderTool::getPathToIDMapping( $publisher->attribute('path') );

                // If PublisherFolderId is included in url, we only take care about this publisher folder
                if ( isset($publisherFolderId) && $pfids['pfid'] == $publisherFolderId )
                {
                    $rootNodes[] = eZContentObjectTreeNode::fetch($pfids['nid']);
                    $articlePath = $uriArticle;

                    break;
                }
                elseif( !isset($publisherFolderId) )
                {
                    $node = eZContentObjectTreeNode::fetch($pfids['nid']);
                    if($node) {
                        $rootNodes[] = $node;
                        $articlePath = $uriArticle;
                    }
                }
            }
        }

        if ( isset($publisherFolderId) != false && trim($uriArticle) == '' )
            return $app;
        
        if ( !isset($articlePath) || count($rootNodes) == 0 )
            return null;

        $node = self::getNodeFromPath ($articlePath, $rootNodes);

        if ( !$node )
            return null;
        
        $cluster   = $app->applicationLocalized()->attribute( 'cluster_identifier' );
        $isVisible = ObjectVisibilityManager::isVisible( $node->attribute('contentobject_id'), $cluster );

        if ( !$isVisible )
            return null;

        return $node;
    }
    /**
     * @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;
    }
    public function render(array $localApplications, array $data, $clusterIdentifier, array $options = array())
    {
        $domainsInClusters = eZINI::instance( 'merck.ini' )->variable( 'DomainMappingSettings', 'ClusterDomains' );
        $domain = $domainsInClusters[$clusterIdentifier];

        $xml = new DOMDocument( '1.0', 'utf-8' );
        $rss = $xml->createElement( 'rss' );
        $rss->setAttribute( 'version', '2.0' );

        $clusterSiteIni = eZINI::fetchFromFile( "extension/{$clusterIdentifier}/settings/site.ini.append.php" );
        $clusterLanguages = $clusterSiteIni->variable( 'RegionalSettings', 'SiteLanguageList' );
        $clusterLanguage = $clusterLanguages[0];

        $rss->appendChild( $xml->createElement( 'language', $clusterLanguage ) );
        $channel = $xml->createElement( 'channel' );

        foreach ( $data as $applicationId => $appFeed )
        {
            foreach( $appFeed as $appArticles)
            {
                $docs = $appArticles['articles'];

                $linkToOverview = false;
                if (SolrSafeOperatorHelper::featureIsActive('newsletterConfig'))
                {
                    $appsLinkedToOverview = SolrSafeOperatorHelper::feature('newsletterConfig', 'applicationsLinkedToOverview');
                    $applicationIdentifier = $localApplications[$applicationId]->attribute('application_object')->attribute('identifier');
                    $linkToOverview = in_array($applicationIdentifier, $appsLinkedToOverview);
                }
                foreach ( $docs as $doc )
                {
                    $publisherPath = $doc['subattr_publisher_folder___source_id____s'][0];
                    $publisherId   = PublisherFolderTool::getPathToIDMapping($publisherPath);
                    $item = $xml->createElement( 'item' );
                    $item->appendChild( $xml->createElement( 'appid', $applicationId ) );

                    $specialities = $xml->createElement( 'specialties', implode( ',', $doc['subattr_speciality___source_id____s'] ) );
                    $item->appendChild( $specialities );

                    $customertypes = $xml->createElement( 'customertypes', implode( ',', $doc['subattr_customer_type___source_id____s'] ) );
                    $item->appendChild( $customertypes );

                    // Title
                    $xmlTitle = $this->escapeStr( $doc['attr_headline_s']);
                    $isEmptyHeadline = trim($doc['attr_promo_headline_t']) == "";

                    if($clusterIdentifier == 'cluster_pt' && !$isEmptyHeadline){
                        $xmlTitle = $this->escapeStr( $doc['attr_promo_headline_t']);
                    }
                    $title = self::createCDATAElement($xml, 'title', $xmlTitle) ;
                    $item->appendChild($title);

                    // Promo headline
                    $promoHeadline = self::createCDATAElement($xml, 'short_title', $doc['attr_promo_headline_t'] );
                    $item->appendChild( $promoHeadline );

                    // Link
                    $merckIni = eZINI::instance( 'merck.ini' );
                    $urlAdditionalValues = $merckIni->variable( 'RssUrlSettings', 'AdditionalValues' );


                    $urlApplication = $localApplications[$applicationId]->attribute('url_alias');
                    if(isset($doc["is_sdk_b"]) && $doc["is_sdk_b"])
                    {
                        $url = $urlApplication . '/' . $doc['meta_url_alias_ms'][0];
                    }
                    else
                    {
                        $url = $urlApplication . '/' . $publisherId['pfid'] . '/' . $doc['attr_' . $clusterIdentifier . '_url_s'];
                    }

                    if ( $linkToOverview )
                    {
                        $linkUrl = 'http://' . rtrim($domain, '/') . $urlApplication;
                        $link = $xml->createElement( 'link', $linkUrl );
                    }
                    else if ( isset( $urlAdditionalValues[$clusterIdentifier] ) )
                    {
                        $linkUrl = 'http://' . rtrim($domain, '/') . '/' . $urlAdditionalValues[$clusterIdentifier] . $url;
                        $link = $xml->createElement( 'link', $linkUrl  );
                    }
                    else
                    {
                        $linkUrl = 'http://' . rtrim($domain, '/') . $url;
                        $link = $xml->createElement( 'link', urlencode( $linkUrl ) );
                    }


                    $item->appendChild( $link );

                    // Author
                    $author = $xml->createElement( 'author', $doc["attr_author_t"] );
                    $item->appendChild( $author );

                    // Source
                    $text = false;
                    $publisherPath = $doc["subattr_publisher_folder___source_id____s"];
                    if($publisherPath && isset($publisherPath[0]))
                    {
                        /** @var PublisherFolder $publisher */
                        $publisher = PublisherFolder::getPublisherFromPath($publisherPath[0]);
                        if( $publisher && $publisher->getTranslation() )
                        {
                            $text = $publisher->getTranslation()->attribute( 'name' );
                        }
                    }
                    $source = $xml->createElement( 'source', $this->escapeStr( htmlspecialchars($text) ) );
                    $item->appendChild( $source );

                    // Description
                    $text = $this->escapeStr( $doc['attr_promo_description_t'] );
                    $text = ( empty( $text ) ? $this->escapeStr( $doc['attr_core_content_t'] ) : $text );

                    $description = self::createCDATAElement( $xml, 'description', $this->escapeStr( $text ) );
                    $item->appendChild( $description );

                    // Publishdate
                    $onlineDate = DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $doc["attr_online_date_dt"])->format('Y-m-d H:i:s');
                    $date = $xml->createElement( 'publishdate', $onlineDate );
                    $item->appendChild( $date );

                    //creationDate
                    $creationDate = DateTime::createFromFormat("Y-m-d\TH:i:s\Z", $doc["attr_date_dt"])->format('Y-m-d H:i:s');
                    $creationDate = $xml->createElement( 'creationdate', $creationDate );
                    $item->appendChild( $creationDate );

                    $mediaContentTypes = json_decode(base64_decode($doc['attr_media_content_types_' . ClusterTool::clusterIdentifier() . '_bst']), true);
                    $hasImageArray = json_decode(base64_decode($doc['attr_has_image_' . $clusterIdentifier . '_bst']));

                    $images = array();
                    if ( $hasPromoImage = SolrSafeOperatorHelper::hasImageArticleFromSolr( array('has_image' => $hasImageArray), 2 ) )
                    {
                        $path = SolrSafeOperatorHelper::getImageArticleUrl(2,$doc['meta_id_si'], $doc['meta_language_code_ms'], 'dt_full');
                        $url = 'http://' . rtrim($domain, '/') . $path;
                        $images[] = $url;
                        $hasPromoImage = 2;
                    }

                    //media_content
                    if( !$hasPromoImage && (isset($mediaContentTypes['image']) || isset($mediaContentTypes['slide'])) )
                    {
                        $slideCount = isset($mediaContentTypes['image']) ? 1 : $mediaContentTypes['slide'];
                        $slideCount = $slideCount > 3 ? 3 : $slideCount;

                        if ( SolrSafeOperatorHelper::hasImageArticleFromSolr( array ( 'has_image' => $hasImageArray ), 0 ) )
                        {
                            for( $i=0; $i<$slideCount; $i++ )
                            {
                                $path = SolrSafeOperatorHelper::getImageArticleUrl(0,$doc['meta_id_si'], $doc['meta_language_code_ms'], 'dt_full', $imageNumber);
                                $url = 'http://' . rtrim($domain, '/') . $path;
                                $images[] = $url;
                            }
                        }
                    }
                    for( $i=0; $i < 3; $i++ )
                    {
                        $imageNumber = ( $i + 1 );
                        if ( $i >= count($images) )
                        {
                            $url = '';
                        }
                        else
                        {
                            $url = $images[$i];
                        }
                        $imageElement = $xml->createElement( 'image' . $imageNumber, $url );
                        $item->appendChild( $imageElement );
                    }

                    // Top
                    $item->appendChild( $xml->createElement( 'top', $doc['attr_featured_content_b'] == '1' ? 1 : 0 ) );

                    // Readcounter
                    $count = 0;
                    if ( isset( $doc['attr_view_counter_' . $clusterIdentifier . '_i'] ) )
                        $count = $doc['attr_view_counter_' . $clusterIdentifier . '_i'];
                    $item->appendChild( $xml->createElement( 'readcounter', $count ) );
                    
                    // Quizreplies
                    $quizReplies = $doc['attr_media_content_quiz_replies_' . $clusterIdentifier . '____ms'];
                    if( isset($quizReplies) && count($quizReplies) > 0 )
                    {
                        $repliesElement = $xml->createElement( 'quizreplies' );
                        for($i = 0; $i < count($quizReplies); $i++)
                        {
                            $repliesElement->appendChild( $xml->createElement( 'quizreply'.$i, $quizReplies[$i] ) );
                        }
                        $item->appendChild( $repliesElement );
                    }

                    $channel->appendChild( $item );

                    eZContentObject::clearCache();
                }
            }
        }

        $rss->appendChild( $channel );
        $xml->appendChild( $rss );

        $xml->formatOutput = true;

        return $xml->saveXML();
    }