/**
     * 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;
            }
        );
    }
    /**
     * 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;
    }
    /**
     * @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 eZTemplate $tpl
     * @param string $operatorName
     * @param array $operatorParameters
     * @param string $rootNamespace
     * @param string $currentNamespace
     * @param mixed $operatorValue
     * @param array $namedParameters
     */
    function modify($tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters)
    {
        switch ($operatorName)
        {
            /*******************************************************************************/
            /*                             Solr Safe Operators                             */
            /*******************************************************************************/

            case 'ezfind_raw_fetch':
                $operatorValue = SolrSafeOperatorHelper::ezfindRawFetch(
                    $namedParameters['params'],
                    $namedParameters['nodeIdsOnly']
                );
                break;
            case 'getUrlSolr':
                $operatorValue = SolrSafeOperatorHelper::getUrlSolr($namedParameters['solrdata']);
                break;
            case 'getDatesPDFavailable':
                $operatorValue = SolrSafeOperatorHelper::getDatesPDFavailable(
                    $namedParameters['onlineDate'],
                    $namedParameters['daysAvailable']
                );
                break;
            case 'getViewCounter':
                $operatorValue = SolrSafeOperatorHelper::getViewCounter(
                    $namedParameters['remoteId'],
                    $namedParameters['clusterIdentifier']
                );
                break;
            case 'getRatings':
                $operatorValue = SolrSafeOperatorHelper::getRatings(
                    $namedParameters['remoteId'],
                    $namedParameters['clusterIdentifier']
                );
                break;
            case 'getJavascriptFiles':
                $operatorValue = SolrSafeOperatorHelper::getJavascriptFiles(
                    $namedParameters['application_name'],
                    $namedParameters['type'],
                    $namedParameters['isConsult']
                );
                break;
            case 'getLessFiles':
                $operatorValue = SolrSafeOperatorHelper::getLessFiles(
                    $namedParameters['application_name'],
                    $namedParameters['application'],
                    $namedParameters['isConsult']
                );
                break;
            case 'getInfosApp':
                $operatorValue = SolrSafeOperatorHelper::getInfosApp($namedParameters['application_identifier']);
                break;
            case 'getHostNameFromURL':
                $operatorValue = SolrSafeOperatorHelper::getHostNameFromURL($namedParameters['url']);
                break;
            case 'context':
                $operatorValue = SolrSafeOperatorHelper::context($namedParameters['url']);
                break;
            case 'getMetas':
                $operatorValue = SolrSafeOperatorHelper::getMetas($namedParameters['applicationName']);
                break;
            case 'getSolrData':
                $operatorValue = SolrSafeOperatorHelper::getSolrData(
                    $namedParameters['remoteId'],
                    $namedParameters['clusterIdentifier'],
                    $namedParameters['extended_fields']
                );
                break;
            case 'getCustomParameter':
                $operatorValue = SolrSafeOperatorHelper::getCustomParameter(
                    $namedParameters['application'],
                    $namedParameters['parameter_name'],
                    $namedParameters['context']
                );
                break;
            case 'getAppIdentifierForIcon':
                $operatorValue = SolrSafeOperatorHelper::getAppIdentifierForIcon($namedParameters['application']);
                break;
            case 'getApplicationUrl':
                $operatorValue = SolrSafeOperatorHelper::getApplicationUrl($namedParameters['identifier']);
                break;
            case 'mappingNameSpe':
                $operatorValue = SolrSafeOperatorHelper::mappingNameSpe($namedParameters['specialtie']);
                break;
            case 'getMappingSpe':
                $operatorValue = SolrSafeOperatorHelper::getMappingSpe();
                break;
            case 'getCustomerTypes':
                $operatorValue = SolrSafeOperatorHelper::getCustomerTypes();
                break;
            case 'getMainSpecialities':
                $operatorValue = SolrSafeOperatorHelper::getMainSpecialities();
                break;
            case 'getUserSpecialities':
                $operatorValue = SolrSafeOperatorHelper::getUserSpecialities();
                break;
            case 'noSeoLink':
                $operatorValue = SolrSafeOperatorHelper::noSeoLink($operatorValue);
                break;
            case 'getTaxoTranslation':
                $operatorValue = SolrSafeOperatorHelper::getTaxoTranslation(
                    $namedParameters['identifier'],
                    $namedParameters['remote_id']
                );
                break;
            case 'cluster_ini':
                $operatorValue = SolrSafeOperatorHelper::clusterIni(
                    $namedParameters['section'],
                    $namedParameters['variable'],
                    $namedParameters['ini_file']
                );
                break;
            case 'truncateContentRelated':
                $operatorValue = SolrSafeOperatorHelper::truncateContentRelated($namedParameters['text']);
                break;
            case 'myCertificatesEnabled':
                $operatorValue = SolrSafeOperatorHelper::featureIsActive("MyCertificates");
                break;
            case 'appHasSpeciality':
                $operatorValue = SolrSafeOperatorHelper::appHasSpeciality();
                break;
            case 'setClusterIdentifier':
                // No $operatorValue modification is normal
                SolrSafeOperatorHelper::setClusterIdentifier($namedParameters['clusterIdentifier']);
                break;
            case 'featureIsActive':
                $operatorValue = SolrSafeOperatorHelper::featureIsActive($namedParameters['featureCode']);
                break;
            case 'feature':
                $operatorValue = SolrSafeOperatorHelper::feature(
                    $namedParameters['featureCode'],
                    $namedParameters['value']
                );
                break;
            case 'alphabet':
                $operatorValue = SolrSafeOperatorHelper::alphabet();
                break;
            case 'generateIso6391':
                $operatorValue = SolrSafeOperatorHelper::generateIso6391($namedParameters['regionalSettingsLocale']);
                break;
            case 'staticfile':
                $operatorValue = SolrSafeOperatorHelper::staticFile(
                    $operatorValue,
                    $namedParameters['quote'],
                    $namedParameters['skip_slash']
                );
                break;
            case 'showHelpDeskPhoneInHeader':
                $operatorValue = !(SolrSafeOperatorHelper::feature('HelpDeskSettings', 'HidePhoneNumberInHeader'));
                break;
            case 'showHelpDeskPhoneOnPage':
                $operatorValue = !(SolrSafeOperatorHelper::feature('HelpDeskSettings', 'HidePhoneNumberOnPage'));
                break;
            case 'getFooterHTML':
                $operatorValue = SolrSafeOperatorHelper::getFooterHTML($namedParameters['footerBlockIdentifier']);
                break;
            case 'getLocaleBySystemCode':
                $operatorValue = SolrSafeOperatorHelper::getLocaleBySystemCode($namedParameters['systemCode']);
                break;
            case 'buildExitUrl':
                $operatorValue = SolrSafeOperatorHelper::buildExitUrl($namedParameters['url']);
                break;
            case 'getUserToken':
                $operatorValue = SolrSafeOperatorHelper::getUserToken();
                break;
            case 'clusterHasFeaturedChannel':
                $operatorValue = SolrSafeOperatorHelper::clusterHasFeaturedChannel();
                break;
            case 'aliasDimensions':
                $operatorValue = SolrSafeOperatorHelper::aliasDimensions($namedParameters['alias']);
                break;
            case 'hasImageArticleFromSolr':
                $operatorValue = SolrSafeOperatorHelper::hasImageArticleFromSolr(
                    $namedParameters['solrdata'],
                    $namedParameters['media_case']
                );
                break;
            case 'getImageArticleUrl':
                $operatorValue = SolrSafeOperatorHelper::getImageArticleUrl(
                    $namedParameters['media_case'],
                    $namedParameters['object_id'],
                    $namedParameters['language'],
                    $namedParameters['alias']
                );
                break;
            case 'getImageArticleUrlFromSolr':
                $operatorValue = SolrSafeOperatorHelper::getImageArticleUrl(
                    $namedParameters['media_case'],
                    $namedParameters['solrdata']['object_id'],
                    $namedParameters['solrdata']['language'],
                    $namedParameters['alias']
                );
                break;
            case 'isHidden':
                $operatorValue = SolrSafeOperatorHelper::isHidden($namedParameters['contentobject_id']);
                break;
            case 'isObjectGloballyVisible':
                $operatorValue = SolrSafeOperatorHelper::isObjectGloballyVisible($namedParameters['contentobject_id']);
                break;
            case 'getClusterVisibilities':
                $operatorValue = SolrSafeOperatorHelper::getClusterVisibilities($namedParameters['contentobject_id']);
                break;
            case 'parseTranslationTagParams':
                $operatorValue = SolrSafeOperatorHelper::parseTranslationTagParams($namedParameters['params']);
                break;
            case 'isSendToColleagueDisabled':
                $operatorValue = SolrSafeOperatorHelper::featureIsActive('DisableSendToColleague')
                    ? SolrSafeOperatorHelper::feature('DisableSendToColleague', 'IsDisabled')
                    : false;
                break;
            case 'getListOfValueOptions':
                $operatorValue = SolrSafeOperatorHelper::getListOfValueOptions( $namedParameters['business_name'], $namedParameters['filter'] );
                break;
            case 'getListOfValues':
                $operatorValue = SolrSafeOperatorHelper::getListOfValues( $namedParameters['business_name'], $namedParameters['filter'] );
                break;
            case 'solrDateToStamp':
                $operatorValue = strtotime($namedParameters['date']) > 3600*24*2 ? SolrTool::getTimestampFromSolr($namedParameters['date']) : 0;
                break;
            case 'getSeoParam':
                $operatorValue = SolrSafeOperatorHelper::getSeoParam($namedParameters['applicationLocalized'], $namedParameters['name'], $namedParameters['params']);
                break;
            case 'applicationHasSeoSpeciality':
                $operatorValue = SolrSafeOperatorHelper::applicationHasSeoSpeciality($namedParameters['applicationIdentifier']);
                break;
            case 'seoIsEnabled':
                $operatorValue = SolrSafeOperatorHelper::seoIsEnabled($namedParameters['applicationIdentifier']);
                break;
            case 'includeEsi':
                $operatorValue = SolrSafeOperatorHelper::includeEsi( $namedParameters['src'], $namedParameters['debug'] );
                break;
            case 'imageDecHash':
                $operatorValue = SolrSafeOperatorHelper::imageDecHash( $operatorValue );
                break;
            case 'bannerDecHash':
                $operatorValue = SolrSafeOperatorHelper::bannerDecHash( $operatorValue );
                break;
            case 'getAndStoreGPNotebookHS':
                $operatorValue = self::getAndStoreGPNotebookHS( );
                break;
            case 'isPromoTaxonomyVisible':
                $operatorValue = SolrSafeOperatorHelper::isPromoTaxonomyVisible( $namedParameters['values'] );
                break;
            case 'translateTaxonomy':
                $operatorValue = SolrSafeOperatorHelper::translateTaxonomy( $namedParameters['code'] );
                break;
            case 'getPublisherArticleUrl':
                $operatorValue = SolrSafeOperatorHelper::getPublisherArticleUrl( $namedParameters['publisher'], $namedParameters['articleId'] );
                break;
        }
    }
    /**
     * @return array
     */
    public function getSocialInfos()
    {
        if( !($this->node instanceof eZContentObjectTreeNode)
            || $this->node->attribute('class_identifier') != 'article' )
            return array();

        /* @type eZContentObjectAttribute[] $dataMap */
        $dataMap     = $this->node->dataMap();
        $headline    = $dataMap["headline"]->content();
        $urlParams   = array();
        $description = "";
        $imageUrl    = "";
        $urlGet      = "";

        if ( ClusterTool::isTwoLangCluster() )
        {
            $urlParams['ll'] = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'exact_target' );
        }

        if($dataMap["promo_description"]->hasContent())
        {
            $description = strip_tags($dataMap["promo_description"]->content());
        }

        if ( count($urlParams) > 0 )
        {
            $urlGet = '?' . http_build_query($urlParams);
        }

        if ( NodeOperatorHelper::hasImageArticle($this->node, ImageArticleTool::SLIDE_APPLICATION_CASE ) )
        {
            $imageUrl = SolrSafeOperatorHelper::getImageArticleUrl(
                ImageArticleTool::SLIDE_APPLICATION_CASE,
                $this->node->attribute('contentobject_id'),
                $this->node->currentLanguage(),
                'dt_full'
            );
            $imageUrl .= $urlGet;
        }

        return array(
            "title"       => $headline,
            "description" => $description,
            "url"         => $this->applicationName()."/".$this->node->remoteID().$urlGet,
            "imageUrl"    => $imageUrl
        );
    }
    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();
    }