/**
  * @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)
     {
         case 'getUrlNode':
             $operatorValue = NodeOperatorHelper::getUrlNode(
                 $namedParameters['applicationName'],
                 $namedParameters['node']
             );
             break;
         case 'getMediaContent':
             $operatorValue = NodeOperatorHelper::getMediaContent($namedParameters['node']);
             break;
         case 'getPictosMedia':
             $operatorValue = NodeOperatorHelper::getPictosMedia(
                 $namedParameters['node'],
                 $namedParameters['with_media_duration']
             );
             break;
         case 'getMediaDuration':
             $operatorValue = NodeOperatorHelper::getMediaDuration($namedParameters['media_object_id']);
             break;
         case 'getOverridePath':
             $operatorValue = NodeOperatorHelper::getOverridePath(
                 $namedParameters['node'],
                 $namedParameters['path']
             );
             break;
         case 'getApplicationIdentifierFromNode':
             $operatorValue = NodeOperatorHelper::getApplicationIdentifierFromNode($namedParameters['node']);
             break;
         case 'getPublisherFolder':
             $operatorValue = NodeOperatorHelper::getPublisherFolder(
                 $namedParameters['node'],
                 $namedParameters['application'],
                 $namedParameters['is_solr_data']
             );
             break;
         case 'sortNodesByMainPriority':
             $operatorValue = NodeOperatorHelper::sortNodesByMainPriority($namedParameters['nodes']);
             break;
         case 'hasImageArticle':
             $operatorValue = NodeOperatorHelper::hasImageArticle(
                 $namedParameters['node'],
                 $namedParameters['media_case']
             );
             break;
         case 'getCurrentNodeLanguage':
             $operatorValue = NodeOperatorHelper::getCurrentNodeLanguage($namedParameters['node']);
             break;
         case 'getMediaCount':
             $operatorValue = NodeOperatorHelper::getMediaCount($namedParameters['node']);
             break;
         case 'getPublisherNodeIdFromArticleNode':
             $operatorValue = NodeOperatorHelper::getPublisherNodeIdFromArticleNode(
                 $namedParameters['article_node']
             );
             break;
         case 'getRemoteComuniti':
             $operatorValue = NodeOperatorHelper::getRemoteComuniti(
                 $namedParameters['object_id'],
                 $namedParameters['remote_id']
             );
             break;
         case 'isHierarchyNode':
             $operatorValue = NodeOperatorHelper::isHierarchyNode(
                 $namedParameters['node']
             );
             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
        );
    }
    /**
     * The modify method gets the current content object AND the list of
     * Solr Docs (for each available language version).
     *
     * @param eZContentObject $contentObject
     * @param eZSolrDoc[] $docList
     */
    public function modify( eZContentObject $contentObject, &$docList )
    {
        /* @var eZContentObjectTreeNode $contentMainNode */
        $contentMainNode        = $contentObject->mainNode();
        $contentObjectLanguages = $contentObject->allLanguages();
        $articleLanguageArray   = array_keys($contentObjectLanguages);
        $publisherFolderNodeId  = PublisherFolderTool::getPublisherNodeIdFromArticleNode($contentMainNode);
        $isMerckManualShowcase  = false;
        // Depth : 0 => father article, 1+ => child article
        $articleRelativeDepth   = $contentMainNode->attribute('depth') - 4;

        if ( is_null($publisherFolderNodeId) )
            return;

        $publisherFolderInfos = PublisherFolderTool::getPublisherFolderInfosFromNodeId($publisherFolderNodeId);
        
        if ( !$publisherFolderInfos )
            return;

        $publisherFolderRelations = PublisherFolderTool::getPublisherFolderRelations($publisherFolderInfos['path']);

        if ( !$publisherFolderRelations || count($publisherFolderRelations['clusters']) === 0 )
            return;

        // node remote
        $remote = $contentMainNode->attribute("remote_id");
        $this->addValueToDoc( $docList, 'attr_node_remote_s', $remote);
        $this->addValueToDoc( $docList, 'attr_relative_depth_i', $articleRelativeDepth);

        foreach ( $publisherFolderRelations['clusters'] as $cluster => $applications )
        {
            ClusterTool::setCurrentCluster( $cluster );
            
            $applicationIdentifier = $applications[0];

            /* @var $applicationLocalized ApplicationLocalized */
            $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );

            if ( !($applicationLocalized instanceof ApplicationLocalized) )
            {
                if (count($applications) == 1)
                {
                    unset($publisherFolderRelations['clusters'][$cluster]);
                    continue;
                }

                $applicationIdentifier = $applications[1];
                $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );

                if ( !($applicationLocalized instanceof ApplicationLocalized) )
                {
                    unset($publisherFolderRelations['clusters'][$cluster]);
                    continue;
                }
                
                $publisherFolderRelations['clusters'][$cluster] = array ($applicationIdentifier);
            }

            // visibility per cluster
            $isVisible = ObjectVisibilityManager::isVisible($contentMainNode->attribute('contentobject_id'), $cluster);

            $this->addValueToDoc( $docList, 'attr_is_invisible_' . $cluster . '_b', !$isVisible );

            if (!isset(self::$_applicationIdentifierToId[$applicationIdentifier]))
                self::$_applicationIdentifierToId[$applicationIdentifier] = $applicationLocalized->applicationObject()->attribute ('id');

            $publisherFolder              = $applicationLocalized->getPublisherFolderFromPath($publisherFolderInfos['path']);
            $publisherLanguages           = $publisherFolder->getLanguages();
            $publisherAndArticleLanguages = array_intersect($publisherLanguages, $articleLanguageArray);

            if ( count($publisherAndArticleLanguages) == 0 )
                continue;

            $primaryLanguage = reset($publisherAndArticleLanguages);
            $contentMainNode->setCurrentLanguage($primaryLanguage);

            // publisher folder languages
            $languageKey       = 'subattr_language_' . $cluster . '____s';
            $formatedLanguages = array_map(
                array('kezfSolrArticleIndex', 'languageCode') ,
                $publisherAndArticleLanguages
            );

            $indexLanguages = array_unique( $formatedLanguages );

            $this->addValueToDoc( $docList, $languageKey, $indexLanguages, true, false );
            
            // Meck manual sections
            if( $applicationIdentifier == MerckManualShowcase::mainApplicationIdentifier() )
                $isMerckManualShowcase = true;

            // url computation
            /* @var eZContentObjectAttribute[] $dataMap */
            $dataMap = $contentMainNode->dataMap();

            ClusterTool::setCurrentCluster( $cluster );

            if( $applicationIdentifier == MerckManualShowcase::mainApplicationIdentifier() )
            {
                $urlContent = preg_replace(
                    '#^([^/]+/){2}#',
                    '',
                    MerckManualFunctionCollection::getMerckManualNodeUrl(
                        $applicationIdentifier,
                        $contentMainNode,
                        $primaryLanguage
                    )
                );
            }
            else
                $urlContent = preg_replace( '#^([^/]+/){2}#', '', $contentMainNode->urlAlias() );

            $this->addValueToDoc( $docList, 'attr_' . $cluster . '_url_s', $urlContent);

            $hasImage = array();

            for ( $mediaCase = 0; $mediaCase<=2; $mediaCase++ )
            {
                $hasImage[$mediaCase] = NodeOperatorHelper::hasImageArticle($contentMainNode, $mediaCase);
            }

            self::addValueToDoc( $docList, 'attr_has_image_' . $cluster . '_bst', base64_encode(json_encode($hasImage)) );

            $db = MMDB::instance();

            // index rating
            $row = $db->arrayQuery(sprintf("SELECT * FROM mm_rating_remote WHERE cluster_identifier = '%s' AND remote_id = '%s'", $cluster, $contentObject->remoteID()));
            if(count($row) && $row[0]["counter"] > 5 )
            {
                self::addValueToDoc( $docList, 'attr_content_rating_'.$cluster.'_f', $row[0]["total"]/$row[0]["counter"] );
                //update to_reindex
                $db->query(sprintf("UPDATE mm_rating_remote SET to_reindex=0 WHERE cluster_identifier = '%s' AND remote_id = '%s'", $cluster, $contentObject->remoteID()));
            }

            // index views
            $row = $db->arrayQuery(sprintf("SELECT * FROM mm_readcount_remote WHERE cluster_identifier = '%s' AND remote_id = '%s'", $cluster, $contentObject->remoteID()));
            if(count($row) && $row[0]["count"] > 0 )
            {
                self::addValueToDoc( $docList, 'attr_view_counter_'.$cluster.'_i', $row[0]["count"] );
                //update to_reindex
                $db->query(sprintf("UPDATE mm_readcount_remote SET to_reindex=0 WHERE cluster_identifier = '%s' AND remote_id = '%s'", $cluster, $contentObject->remoteID()));
            }

            if( $dataMap && $dataMap['media_content']->hasContent() )
            {
                $mediaContent      = $dataMap['media_content']->content();
                $mediaRelationList = $mediaContent['relation_list'];
                $entries           = array();
                $firstLink         = true;
                $totalQuizzes      = 0;

                foreach ( $mediaRelationList as $mediaRelation )
                {
                    $mediaObjectId = $mediaRelation['contentobject_id'];
                    $mediaClass = $mediaRelation['contentclass_identifier'];

                    /*******************************************************************************
                     * TODO : Adapt after PF Refactor
                     *******************************************************************************/
                    if ( !in_array($mediaClass, array('image', 'quiz', 'link')) )
                        continue;

                    
                    if ( $mediaClass === 'image' )
                    {
                        if ( count( $entries ) >= 3 )
                            continue;

                        // Language is DEPRECATED, Fake Language instead
                        $entries[] = $mediaObjectId . ";dep-DP";
                        /*******************************************************************************
                         * TODO : End : Adapt after PF Refactor
                         *******************************************************************************/
                    }
                    elseif ( ( $mediaClass === 'link' && $firstLink ) || $mediaClass === 'quiz' )
                    {
                        $mediaObject = eZContentObject::fetch( $mediaObjectId );

                        if ( !$mediaObject )
                            continue;

                        /* @var eZContentObjectAttribute[] $mediaDatamap */
                        $mediaDatamap = $mediaObject->dataMap();

                        if ( !is_array($mediaDatamap) )
                            continue;

                        if ( $mediaClass === 'link' )
                        {
                            if (!$mediaDatamap['url']->hasContent())
                                continue;

                            $firstLink = false;

                            self::addValueToDoc( $docList, 'attr_media_content_link_' . $cluster . '____ms', $mediaDatamap['url']->content(), false );
                        }
                        elseif ( $mediaClass === 'quiz' )
                        {
                            if ( $mediaDatamap['replies']->hasContent() )
                            {
                                $quizReplies = $mediaDatamap['replies']->content();
                                $quizReplies = $quizReplies->attribute('columns');
                                $quizReplies = $quizReplies['sequential'][1]['rows'];

                                if ( count($quizReplies) > 0 )
                                    self::addValueToDoc( $docList, 'attr_media_content_quiz_replies_' . $cluster . '____ms', $quizReplies, true);
                            }

                            if ( !empty($mediaDatamap['question']->DataText) )
                            {
                                self::addValueToDoc( $docList, 'attr_media_content_quiz_question_' . $cluster . '_ms', trim(strip_tags($mediaDatamap['question']->DataText)), false );
                            }

                            if ( !$mediaDatamap['points']->hasContent() )
                                continue;

                            $totalQuizzes+= $mediaDatamap['points']->content();
                        }
                    }
                }

                $withMediaDuration    = true;
                $typeMedias           = NodeOperatorHelper::getPictosMedia( $contentMainNode, $withMediaDuration );
                $typeMediasSerialized = base64_encode( json_encode($typeMedias) );

                // getPictosMedia as solr field
                self::addValueToDoc( $docList, 'attr_media_content_types_' . $cluster . '_bst', $typeMediasSerialized, false );

                // getMediaCount as solr field
                $mediaCount = NodeOperatorHelper::getMediaCount($contentMainNode);
                self::addValueToDoc( $docList, 'attr_media_content_count_' . $cluster . '_i', $mediaCount, false );

                // Used only for Quizz
                if ( $totalQuizzes > 0 )
                    self::addValueToDoc( $docList, 'attr_media_content_quiz_points_' . $cluster . '_i', $totalQuizzes, false );
            }
            
            unset($isHidden);
        }

        ClusterTool::resetCurrentCluster();

        $concernedNode = $contentMainNode;
        $concernedNode->setCurrentLanguage($articleLanguageArray[0]);

        if ( $contentMainNode->attribute('depth') > 4 )
        {
            $concernedNode = $contentMainNode->fetchParent();
            $concernedNode->setCurrentLanguage($articleLanguageArray[0]);
        }

        /* @type $concernedDM eZContentObjectAttribute[] */
        $concernedDM = $concernedNode->dataMap();
        $tags        = $concernedDM['tags'];

        $MerckManualAboutSectionId = eZIni::instance('merck.ini')->variable('MerckManualAboutSettings', 'SectionSourceId');
        $taxonomiesAttribute       = $concernedDM['serialized_taxonomies'];

        if( $taxonomiesAttribute instanceof eZContentObjectAttribute && $taxonomiesAttribute->hasContent() )
        {
            $taxonomies = $taxonomiesAttribute->content();

            foreach( array_keys($publisherFolderRelations['clusters']) as $cluster )
            {
                self::addValueToDoc(
                    $docList,
                    "attr_exclude_from_search_{$cluster}_b",
                    $MerckManualAboutSectionId && in_array($MerckManualAboutSectionId, $taxonomies['section']),
                    false
                );
            }
        }

        if( $tags instanceof eZContentObjectAttribute && $tags->hasContent() )
            self::addValueToDoc( $docList, 'subattr_tags____ms', explode("|", $tags->content()) );

        if ( $isMerckManualShowcase )
            $this->processSpecificMerckManual($docList, $concernedNode, $concernedDM, $publisherFolderRelations);

        foreach ( $publisherFolderRelations['clusters'] as $cluster => $applications )
        {
            ClusterTool::setCurrentCluster( $cluster );

            foreach( $applications as $key => $applicationIdentifier )
            {
                if ( !isset(self::$_applicationIdentifierToId[$applicationIdentifier]) )
                {
                    $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );

                    if( !($applicationLocalized instanceof ApplicationLocalized) )
                    {
                        eZDebug::writeError(
                            sprintf('Cluster: %s; Identifier: %s; ObjectId: %s', $cluster, $applicationIdentifier, $contentObject->attribute('id') ),
                            'Error getting application localized' );
                        unset( $publisherFolderRelations['clusters'][$cluster][$key] );
                    }
                    else
                        self::$_applicationIdentifierToId[$applicationIdentifier] = $applicationLocalized->applicationObject()->attribute('id');
                }
            }
        }

        ClusterTool::resetCurrentCluster();
        
        $applicationIds = array();

        foreach ( $publisherFolderRelations['clusters'] as $cluster => $applications )
            foreach( $applications as $applicationIdentifier )
                $applicationIds[] = self::$_applicationIdentifierToId[$applicationIdentifier];

        $uniqueApplicationIds = array_unique($applicationIds);

        foreach( $docList as $languageCode => $doc )
        {
            $dataMap               = $contentObject->fetchDataMap(false, $languageCode);
            $headline              = $dataMap['headline']->content();
            $headlineLowerCase     = mb_strtolower( StringTool::removeAccents($headline, 'utf-8', false), 'utf-8' );
            $unaccentedFirstLetter = mb_substr($headlineLowerCase, 0, 1, 'utf-8');

            $doc->addField( 'attr_headline_first_letter_lc_s', $unaccentedFirstLetter );
            $doc->addField( 'attr_headline_lc_s', $headlineLowerCase );

            foreach( $uniqueApplicationIds as $id )
            {
                $doc->addField( 'subattr_local_application___source_id____s', $id );
            }

            foreach( $publisherFolderRelations['clusters'] as $cluster => $applications )
            {
                foreach( $applications as $applicationIdentifier )
                {
                    $doc->addField('subattr_local_application___source_mixed____s', $cluster . '##unused##' . self::$_applicationIdentifierToId[$applicationIdentifier]);
                }
            }
        }
    }