/**
     * @param string $term
     * @param bool $wal
     * @return array
     */
    protected function mcSearch( $term, $wal )
    {
        $session = curl_init();
        curl_setopt( $session, CURLOPT_URL, $this->anonymousUrl . "/solr/$term/json" );
        curl_setopt( $session, CURLOPT_HEADER, false );
        curl_setopt( $session, CURLOPT_RETURNTRANSFER, true );
        curl_setopt( $session, CURLOPT_FOLLOWLOCATION, true );
        $response = curl_exec( $session );
        curl_close( $session );
        $response = json_decode( $response, true );

        $displayedTerm = mb_strlen( $term ) > 34 ? mb_substr( $term, 0, 34 ) . '...' : $term;
        $result = array(
            'term'      => str_replace( '+', ' ', $term ),
            'count'     => $response['count'],
            'resultUrl' => $response['resultUrl'],
            'mcAppUrl'  => CacheApplicationTool::buildLocalizedApplicationByIdentifier( 'merck-connect' )->applicationUrl() . "#?s=$term",
            'message'   => ezpI18n::tr( "merck/merck_connect", "%nbresult RESULTS FOR <strong>%searchterm</strong> ON MERCK CONNECT", null, array(
                "%nbresult"   => $response['count'],
                "%searchterm" => str_replace( '+', ' ', $displayedTerm )
            ) ) . ' &gt',
        );
        if( $wal && self::user() )
        {
            $result['al'] = $this->anonymousUrl . '/genericsearch.xhtml?q=' . $term . '&ltoken=' . $this->getAutologinLink( true );
        }
        if( $wal && !self::user() )
        {
            $result['al'] = $this->anonymousUrl;
        }

        return $result;
    }
    /**
     * @return ApplicationObject[]
     */
    public function getAppsToAdd()
    {
        $applications = array();

        $env = new MMEnvironment();
        $controller = new MMHomePageController();
        $zones = $controller->fetchZones( $env->currentId() );
        foreach( $zones['right'] as $block )
        {
            if( $block->Type == MMBlock::TYPE_CAROUSEL )
            {
                $apps = json_decode( $block->Content );
                foreach( $apps->application_list as $appId )
                {
                    $appLocalized = CacheApplicationTool::buildLocalizedApplicationByLocalizedId( $appId );
                    if( !$appLocalized )
                    {
                        continue;
                    }                    
                    $applications[] = $appLocalized->applicationObject();
                }
            }
        }

        return $applications;

    }
    public function parseRequestParams()
    {
        parent::parseRequestParams();

        $catchAppNameEnabled = MMGlobalSearch::isCatchUpAppNameEnabled();

        if ( $catchAppNameEnabled )
        {
            $applicationList = array();
            $result          = ApplicationSearch::search( $this->searchQuery );

            if ( $result['response']['numFound'] > 0 )
            {
                foreach ( $result['response']['docs'] as $row )
                {
                    $application = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $row['identifier_s'] );
                    if ( $application instanceof ApplicationLocalized )
                    {
                        $applicationList[$row['identifier_s']] = array(
                            'identifier' => $row['identifier_s'],
                            'name'       => $row['name_s'],
                            'url'        => $application->applicationUrl()
                        );
                    }
                }

                $this->contentList->pushResult( 'application_list' , $applicationList );
            }
        }

        $this->withAllSpecialities = false;
        $this->withT3Facets = false;
    }
    /**
     *
     */
    public function initVars()
    {
        $this->application = CacheApplicationTool::buildLocalizedApplicationByIdentifier($this->applicationIdentifier);

        $tab = FacetFilteringTool::getTaxonomyTranslation('speciality');
        foreach($tab as $key => $val)
        {
            $this->specialityIds[] = $key;
        }
    }
 /**
  * @return string
  */
 public function publishersFilter()
 {
     $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( MerckManualShowcase::mainApplicationIdentifier() );
     if ( $applicationLocalized instanceof ApplicationLocalized )
     {
         return $applicationLocalized->getPublishersFilter();
     }
     else
     {
         return null;
     }
 }
    /**
     * Creates a new instance
     *
     * @param int $appId Localized Application Id
     * @param int $nbArticles Number of articles
     * @param int $viewMode View mode to use
     * @param int $publisherId Id of Publisher
     * @param int $selectionType Selection type to use
     **/
    public function __construct( $appId, $nbArticles, $viewMode, $publisherId, $selectionType )
    {
        $this->applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByLocalizedId($appId);
        $this->applicationObject    = $this->applicationLocalized->applicationObject();
        $this->nbArticles           = $nbArticles;
        $this->viewMode             = $viewMode;
        $this->publisherId          = $publisherId;
        $this->selectionType        = $selectionType;
        $applicationName            = $this->applicationLocalized->attribute('url');

        if($applicationName)
            $this->_application = ApplicationFactory::fetchByUri( '/'.$applicationName );
    }
    /**
     * Fetches and returns a list of localized applications
     *
     * @return ApplicationLocalized[]
     **/
    protected function fetchApplications()
    {
        $apps = array();
        foreach( $this->appIdList as $appId )
        {
            $app = CacheApplicationTool::buildLocalizedApplicationByLocalizedId($appId);
            if( !$app )
            {
                continue;
            }
            $apps[] = $app;

        }
        return $apps;
    }
    /**
     * @param string $clusterIdentifier
     * @param string $applicationIdentifier
     * @param string $bannerType
     * @return string
     */
    public static function getStaticPath( $clusterIdentifier, $applicationIdentifier, $bannerType )
    {
        if ( $clusterIdentifier !== ClusterTool::clusterIdentifier() )
        {
            ClusterTool::setCurrentCluster($clusterIdentifier);
        }
        $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );
        if ( !($applicationLocalized instanceof ApplicationLocalized) )
        {
            return null;
        }
        $bannerArray = $applicationLocalized->getBanners();
        if( isset( $bannerArray[$bannerType] ) && !empty( $bannerArray[$bannerType] ) )
        {
            return preg_replace( '#/extension#', 'extension/', $bannerArray[$bannerType] );
        }

        return null;
    }
    /**
     * @return string[]
     */
    protected function translations()
    {
        if( is_null($this->_translations) )
        {
            $translations = array();
            /* @var $applicationLocalized ApplicationLocalized */
            foreach( CacheApplicationTool::clusterApplications() as $k => $applicationLocalized )
            {
                if( !is_object( $applicationLocalized ) )
                {
                    eZDebug::writeError( 'Could not load applicationLocalized for '.$k );
                    continue;
                }
                $translations[$applicationLocalized->attribute('application_id')] = $applicationLocalized->attribute('name');
            }
            $this->_translations = $translations;
        }

        return $this->_translations;
    }
    /**
     * @param int $applicationId
     * @return array[]
     */
    public static function fetchAllowedUsersByApplication($applicationId)
    {
        $appLocalized = CacheApplicationTool::buildLocalizedApplicationByApplication($applicationId);
        $conditions = array(
            'application_localized_id'                 => $appLocalized->id,
        );

        $result = parent::fetchObjectList(self::definition(), null, $conditions, null, null, false );
        $usersList = array();

        foreach( $result as $row )
        {
            if ( !empty($row) )
            {
                $usersList[] = $row['user_uuid'];
            }
        }

        return $usersList;
    }
    /**
     * @return bool
     */
    public function htmlBuildResult()
    {
        parent::htmlBuildResult();

        $applicationIds = CountryApplicationLibrary::fetchAuthorizedApplicationIds();

        foreach( $applicationIds as $k => $v )
        {
            if(!$v)
                unset($applicationIds[$k]);
        }

        $applicationIds                  = array_values($applicationIds);
        $applications                    = ApplicationLocalized::fetchApplicationList( array('id' => array($applicationIds)) );
        $applicationWebtrendsIdentifiers = array();

        foreach( $applications as $k => $app )
        {
            /* @var $app ApplicationObject */
            $applicationWebtrendsParams = $app->applicationLocalized()->webtrendsParams();

            if( trim($applicationWebtrendsParams['cg_n']) != '' )
                $applicationWebtrendsIdentifiers[strval($app->attribute('id'))] = $applicationWebtrendsParams['cg_n'];
        }

        $this->tpl()->setVariable( 'apps_wb_labels', $applicationWebtrendsIdentifiers );

        /* @var $app ApplicationLocalized */
        foreach( CacheApplicationTool::clusterApplications() as $app )
        {
            if( $app->applicationObject->identifier == 'merck-connect' )
            {
                $this->tpl()->setVariable( 'merck_connect_results', true );
                break;
            }
        }

        return true;
    }
    /**
     * @return string
     */
    public function backUrl()
    {
        $baseUrl    = eZINI::instance()->variable( 'SiteAccessSettings', 'BaseUrl' );
        $serverUrl  = $this->domain();
        $backUrl    = $serverUrl.$baseUrl;

        if( isset( $_SERVER['HTTP_REFERER'] ) && $this->checkRedirectUrl( $_SERVER['HTTP_REFERER'] ) )
        {
            $skipPage   = false;
            $noFullView = false;

            //if we are redirecting to an app we need to check app url if it is external page skipping exit page.
            $appUrl = str_replace($backUrl, '', $_SERVER['HTTP_REFERER']);
            $firstSlashPos = strpos($appUrl, '/');
            if ( $firstSlashPos )
            {
                $appUrl = substr($appUrl, 0, $firstSlashPos);
            }
            $localApp = CacheApplicationTool::buildLocalizedApplication($appUrl);
            if ( $localApp instanceof ApplicationLocalized )
            {
                $skipPage   = $localApp->getCustomParameter( 'SkipExitPage' );
                $noFullView = $localApp->getCustomParameter( 'NoFullView' );
            }

            if ( $skipPage && !$noFullView )
            {
                $backUrl .= 'external/' . $appUrl;
            }
            elseif(!$noFullView)
            {
                $backUrl = $_SERVER['HTTP_REFERER'];
            }
        }

        return $backUrl;
    }
    public function run()
    {
        $type           = isset( $this->options['type'] ) ? $this->options['type'] : null;
        $types          = array( 'login', 'autologin' );
        if ( !in_array( $type, $types ) )
        {
            $typeAnswer     = $this->cli->askQuestion( "Action type", $types );
            $type           = $types[$typeAnswer];
        }
        $this->actionType = $type;

        $credentials = $this->getCredentials();
        $this->cli->cli->output( var_export($credentials, true) );

        if ( !$this->domain() )
        {
            $domainsList = array_keys( $this->domains );
            sort($domainsList);
            $domainAnswer = $this->cli->askQuestion( "For which domain?", $domainsList );
            $domain = $domainsList[$domainAnswer];
            $this->domain( $domain );
        }

        $this->cli->cli->output( "\nChecking ESB Login" );

        $esbResponse = isset($credentials['t'])
            ? $this->checkAutoLogin( $credentials['t'] )
            : $this->checkLogin( $credentials['login'], $credentials['password'] );
        $data = $esbResponse['data'];


        if( !isset( $data['Login']) || $data['Login'] != 'yes' )
            $this->script->shutdown( 1, "Could not log in:\n".print_r( $esbResponse, true ) );

        if( !isset( $data['Username']) || empty( $data['Username'] ) )
            $this->script->shutdown(1, "No Username returned\n".print_r( $esbResponse, true ) );

        /* @var $localizedLoginApplication \ApplicationLocalized */
        $localizedLoginApplication = \CacheApplicationTool::buildLocalizedApplicationByIdentifier( 'login' );
        if ( $data['Data']['Validated'] == 'PV' && $localizedLoginApplication->getCustomParameter( 'RestrictPendingUsers') )
            $this->script->shutdown( 1, "Pending user: \n".print_r( $esbResponse, true) );

        if ( $data['Data']['Validated'] == 'RP' && $localizedLoginApplication->getCustomParameter( 'RestrictRejectedUsers' ) )
            $this->script->shutdown( 1, "Rejected user: \n".print_r( $esbResponse, true) );

        $this->cli->cli->output( "Login looks to be OK" );

        if( $this->script->verboseOutputLevel() )
            $this->cli->cli->output( print_r( $esbResponse, true ) );

        $this->cli->cli->output( "\nChecking ESB Read" );

        $esbResponse = $this->checkRead( $data['Username'] );
        if( $this->script->verboseOutputLevel() )
            $this->cli->cli->output( print_r( $esbResponse, true ) );

        $this->script->shutdown( 0 );
    }
示例#14
0
    /**
     * @param ChannelBlockConfiguration $configuration
     * @param ChannelBlock $block
     * @return string
     */
    private function getLinkMore(ChannelBlockConfiguration $configuration, ChannelBlock $block)
    {
        $query = "/(channel)/".$block->attribute("id");
        if($block->attribute("sorting_method") && $block->attribute("sorting_method") != "")
        {
            $query .= "#?s=".$block->attribute("sorting_method");
        }

        $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByLocalizedId($configuration->attribute("application_localized_id"));
        return $applicationLocalized->applicationUrl().$query;
    }
    /**
     * @return array
     */
    public static function getApplicationLists()
    {
        $userAppList = AppBarControl::instance()->applicationIds();
        $orderedAppList = $userAppList;
        $apps = array();

        sort($orderedAppList);

        $rawApps = ApplicationLocalized::fetchApplicationList(array('id' => array($orderedAppList)));

        foreach ( $rawApps as $k => $app )
        {
            $force = false;
            if(SolrSafeOperatorHelper::featureIsActive('LearningNeedsAssessment') && $app->identifier == 'learning-needs-assessment')
            {
                $force = true;
            }

            if ( $app->attribute('application_library') || $force )
            {
                /* @var $app ApplicationLocalized */
                $apps['#' . $app->attribute('id')] = $app;
            }
            else
            {
                unset($userAppList[array_search($app->attribute('id'), $userAppList)]);
                $userAppList = array_values($userAppList);

                unset($orderedAppList[array_search($app->attribute('id'), $orderedAppList)]);
                $orderedAppList = array_values($orderedAppList);
            }
        }

        // we check if some apps were deleted in the meantime
        if ( self::user() )
        {
            $applistToUpdate = false;

            foreach ( $userAppList as $k => $id )
            {
                if ( !isset($apps['#' . $id]) )
                {
                    // we remove the application from the app bar only if it is not available for the anonymous
                    // display rights are handled at application level
                    if ( !in_array($id, CountryApplicationLibrary::fetchAuthorizedApplicationIds(true)) )
                    {
                        unset($userAppList[$k]);
                        $applistToUpdate = true;
                    }
                    else
                    {
                        $apps['#' . $id] = CacheApplicationTool::buildLocalizedApplicationByApplication($id);
                    }
                }
            }
            if ( $applistToUpdate )
            {
                $userAppList = array_values($userAppList);
                $user = MMUsers::getCurrentUserObject();
                $orderedAppList = $userAppList;

                sort($orderedAppList);

                $user->setApplicationList($userAppList);
            }
        }

        return array(
            'app_list' => self::user() ? $orderedAppList : $userAppList,
            'apps'     => $apps
        );
    }
    /**
     * 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;
            }
        );
    }
    /**
     * @param string$clusterIdentifier
     * @param bool $backupExisting
     * @param bool $includeTimestamp
     * @return array
     * @throws Exception
     */
    public function generateSpriteForCluster($clusterIdentifier, $backupExisting = true, $includeTimestamp = true)
    {
        $outputFile = $this->buildFilePath($this->outputPath, array($clusterIdentifier));
        $timestampOutputFile = $this->generateFileName($outputFile, $includeTimestamp);
        $generatedSpriteName = substr($timestampOutputFile, strrpos($timestampOutputFile, '/') + 1);

        ClusterTool::setCurrentCluster( $clusterIdentifier );

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

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

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

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

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

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

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

        return array(
            'errorCode' => 0,
            'generateSpriteCommand' => $cmd
        );
    }
    /**
     * @return array
     */
    public function getResponseSolr()
    {
        $applicationDictionaryRows = $this->prepareConfig();

        $forbiddenWords = NodeVisibilityCheck::getForbiddenWordsArray( $this->_cluster_identifier );
        $queryTerm = count($forbiddenWords) ? implode(' ', $forbiddenWords) : '*:*';

        foreach ( $applicationDictionaryRows as $applicationDictionaryRow )
        {
            // Get application node_id
            $applicationId = $applicationDictionaryRow['application_id'];

            /** @var ApplicationLocalized[] $_localApplication */
            $this->_localApplications[$applicationId] = CacheApplicationTool::buildLocalizedApplicationByApplication( $applicationId );

            $appLocalizedIsProper = ( $this->_localApplications[$applicationId] instanceof ApplicationLocalized );

            if ( !$appLocalizedIsProper )
            {
                eZDebug::writeError( sprintf( 'Cannot fetch localized application %s for cluster %s', $applicationId, $this->_cluster_identifier ), __FILE__ . '::' . __LINE__ );
                continue;
            }

            /* @type $validLanguages array */
            $newsletterStyle = $applicationDictionaryRow['newsletter_style'];
            $clusterSiteIni  = eZINI::fetchFromFile( "extension/{$this->_cluster_identifier}/settings/site.ini.append.php" );
            $validLanguages  = $clusterSiteIni->variable( 'RegionalSettings', 'SiteLanguageList' );

            // Common
            $fq = array(
                'meta_class_identifier_ms:"article"',
                '(attr_archive_date_dt:"1970-01-01T01:00:00Z" OR attr_archive_date_dt:[NOW TO *])',
                'meta_installation_id_ms:'.eZSolr::installationID(),
                'attr_is_invisible_' . $this->_cluster_identifier . '_b:false',
                'meta_language_code_ms:(' . implode( ' OR ', $validLanguages ) . ')',
            );
            
            $taxonomyList = json_decode( $applicationDictionaryRow['taxonomy_filter'], true );

            if(count($taxonomyList) > 0){
                foreach ($taxonomyList as $row) {
                    foreach($row as $taxonomyCategory => $taxonomies){
                        $taxonomies = array_map(function($value) { return '"' . $value . '"'; }, $taxonomies);
                        $fq[] = "subattr_{$taxonomyCategory}___source_id____s: (" . implode(',', $taxonomies) . ')';
                    }
                }
            }

            // NO SDK
            $publisherNodeIds = $this->_localApplications[$applicationId]->publisherNodeIds();
            if(count($publisherNodeIds) == 1 )
            {
                $newsletterStyle = $applicationDictionaryRow['newsletter_style'];

                $fq = array_merge($fq, array(
                    'meta_path_si:' . $publisherNodeIds[0],
                ));
            }
            elseif (count($publisherNodeIds) > 1 )
            {
                $publisherFilter = implode(' OR ', $publisherNodeIds);
                $newsletterStyle = $applicationDictionaryRow['newsletter_style'];

                $fq = array_merge($fq, array(
                        "meta_path_si:($publisherFilter)",
                    ));
            }
            /**
             * SDK Specific treatment; dead code for now
             *
                if ( $this->_localApplications[$applicationId] instanceof SDKApplication )
                {
                    // SDK application
                    $fq = array_merge($fq, array(
                        'subattr_local_application___source_id____s:' . $applicationId,
                        'is_sdk_b:true AND is_newsletter_b:true'
                    ));
                }
             *
             */

            // Solr query parameters
            $rows = 100000;
            $queryParams = array(
                'indent' => 'on',
                'q' => $queryTerm,
                'start' => 0,
                'rows' => $rows,
                'fq' => $fq,
                'fl' => array(
                    'attr_has_image_' . $this->_cluster_identifier . '_bst',
                    'meta_remote_id_ms',
                    'meta_node_id_si',
                    'meta_main_node_id_si',
                    'attr_featured_content_b',
                    'attr_date_dt',
                    'meta_path_string_ms',
                    'meta_language_code_ms',
                    'attr_view_counter_' . $this->_cluster_identifier . '_i',
                    'subattr_speciality___source_id____s',
                    'subattr_customer_type___source_id____s',
                    'meta_current_version_si',
                    'attr_promo_description_t',
                    'attr_author_t',
                    'attr_source_t',
                    'attr_online_date_dt',
                    'attr_headline_s',
                    'subattr_publisher_folder___source_id____s',
                    'attr_promo_headline_s',
                    'attr_'.$this->_cluster_identifier.'_remote_s',
                    'attr_'.$this->_cluster_identifier.'_node_remote_s',
                    //'attr_media_content_image_'.$this->_cluster_identifier.'____ms',
                    //'attr_promo_image_'.$this->_cluster_identifier.'_s',
                    'is_sdk_b',
                    'meta_url_alias_ms',
                    'attr_promo_headline_t',
                    'subattr_publisher_folder___source_id____s',
                    'meta_id_si',
                    'attr_media_content_types_' . ClusterTool::clusterIdentifier() . '_bst',
                    'attr_' . ClusterTool::clusterIdentifier() . '_url_s',
                    'attr_core_content_t',
                    'subattr_download_ressource___expiration_date____dt',
                    'attr_node_remote_s',
                    'attr_media_content_quiz_replies_' . $this->_cluster_identifier . '____ms',
                    'attr_media_content_quiz_points_' . $this->_cluster_identifier . '_i',
                    'attr_media_content_quiz_question_' . $this->_cluster_identifier . '_ms',
                ),
                'qt' => '',
                'explainOther' => '',
                'hl.fl' => '',
                'sort' => $this->_configuration['sort']
            );
            $publisherFilters = $this->_localApplications[$applicationId]->getPublishersFilter();
            if ( $publisherFilters )
            {
                $queryParams['fq'][] = $publisherFilters;
            }

            if ( !empty($this->_customerType) )
            {
                $customerTypeCondition = implode(',', $this->stringArrayToFilterQueryParam($this->_customerType));
                $queryParams['fq'][] = sprintf( 'subattr_customer_type___source_id____s:(%s)', $customerTypeCondition );
            }
            if ( !empty($this->_specialty) )
            {
                $specialtyCondition = implode(',', $this->stringArrayToFilterQueryParam($this->_specialty));
                $queryParams['fq'][] = sprintf( 'subattr_speciality___source_id____s:(%s)', $specialtyCondition );
            }
            if ( $applicationDictionaryRow["publisher"] )
            {
                $queryParams['fq'][] = sprintf( 'subattr_publisher_folder___source_id____s:(%s)', $applicationDictionaryRow["publisher"] );
            }

            if ( $newsletterStyle == 'PICL' )
            {
                $queryParams['fq'][] = 'subattr_media_type___source_id____s:107.2';
            }

            //taxonomies
            $taxonomies = $this->getApplicationTaxonomies($applicationDictionaryRow['feed_id']);
            $firstCategory = reset(array_keys($taxonomies));
            $queryTaxonomies = '';
            foreach($taxonomies as $categorie=>$taxonomie)
            {
                if($categorie != $firstCategory)
                {
                    $queryTaxonomies .= ' AND ';
                }
                $queryTaxonomies .= 'subattr_' . $categorie . '___source_id____s:(' . $taxonomie . ')';
            }

            if($queryTaxonomies != '')
            {
                $queryParams['fq'][] = $queryTaxonomies;
            }

            $queryParamsFqFallback = $queryParams['fq'];
            $rowValueKey           = '';

            // different sort and filters by mechanism
            switch ($applicationDictionaryRow["mechanism"]) {
                case 1:
                    $rowValueKey = 'number_article_list';
                    $queryParams['sort'] = implode( ', ', $queryParams['sort'] );

                    //if begin/end date is set
                    if(!empty($this->_beginDate) && !empty($this->_endDate))
                    {
                        $queryParams['fq'][] = 'attr_online_date_dt:[' . $this->_beginDate . ' TO ' . $this->_endDate . ']';
                    }
                    else
                    {
                        $queryParams['fq'][] = sprintf( 'attr_online_date_dt:[NOW-%sDAY TO *]', $this->_configuration['days'] );
                    }
                    break;
                case 2:
                    $rowValueKey = 'number_article_random';
                    $oneHourRandom = floor(time() / 3600);
                    $queryParams['sort'] = 'attr_' . $oneHourRandom . '_random asc';
                    break;
                case 4:
                    $rowValueKey = 'number_article_last_x';
                    $queryParams['sort'] = "attr_online_date_dt desc";
                    $queryParams['fq'][] = 'attr_online_date_dt:[NOW-7DAY TO *]';

                    //if begin/end date is set
                    if(!empty($this->_beginDate) && !empty($this->_endDate))
                    {
                        $queryParams['fq'][] = 'attr_online_date_dt:[' . $this->_beginDate . ' TO ' . $this->_endDate . ']';
                    }
                    else
                    {
                        $queryParams['fq'][] = sprintf( 'attr_online_date_dt:[NOW-%sDAY TO *]', $this->_configuration['days'] );
                    }
                    break;
                case 5:
                    $rowValueKey = 'number_article_list';
                    if(!empty($this->_beginDate) && !empty($this->_endDate))
                    {
                        $queryParams['fq'][] = 'attr_online_date_dt:[' . $this->_beginDate . ' TO ' . $this->_endDate . ']';
                    }
                    $queryParams['sort'] = implode( ', ', $queryParams['sort'] );
                    if( $applicationDictionaryRow['number_article_ns'] )
                    {  
                        $queryParams['rows'] = (int)$applicationDictionaryRow['number_article_ns'];
                    }
                    else
                    {
                         $queryParams['rows'] = 100;
                    }
                    break;
            }

            if ( (int) $applicationDictionaryRow[$rowValueKey] >= 0 )
            {
                $queryParams['rows'] = (int) $applicationDictionaryRow[$rowValueKey];
            }

            $queryParams['fl'] = implode( ',', $queryParams['fl'] );
            $queryParams['fq'] = implode( ' AND ', $queryParams['fq'] );

            // main fetch solr
            $result = SolrTool::rawSearch( $queryParams, 'php', false );
            if ( !isset( $result['response']['docs'] ) )
            {
                eZDebug::writeError( 'Error from Solr for query : ' . $result['params']['fq'], __FILE__ . '::' . __LINE__ );
                if( php_sapi_name() != 'cli' )
                {
                    header( 'HTTP/1.x 500 Internal Server Error' );
                    eZExecution::cleanExit();
                }
            }
            if ( count($result['response']['docs']) == 0 && $applicationDictionaryRow['mechanism'] == 5)
            {
                $queryParams['fq'] = $queryParamsFqFallback;
                $queryParams['sort'] = array(
                    'attr_featured_content_b desc',
                    'attr_online_date_dt desc',
                );

                $queryParams['sort'] = implode( ', ', $queryParams['sort'] );

                //if begin/end date is set
                if(!empty($this->_beginDate) && !empty($this->_endDate))
                {
                    $queryParams['fq'][] = 'attr_online_date_dt:[' . $this->_beginDate . ' TO ' . $this->_endDate . ']';
                }
                $queryParams['fq'] = implode( ' AND ', $queryParams['fq'] );
                $result = SolrTool::rawSearch( $queryParams, 'php', false );
            }

            // if no result fallback for mechanism 3
            if ( count( $result['response']['docs'] ) == 0 && $applicationDictionaryRow["mechanism"] == 3 )
            {
                $queryParams['fq'] = $queryParamsFqFallback;
                $queryParams['fq'] = implode( ' AND ', $queryParams['fq'] );
                if ( (int) $applicationDictionaryRow['number_article_random'] >= 0 )
                {
                    $queryParams['rows'] = (int) $applicationDictionaryRow['number_article_random'];
                }
                else
                {
                    $queryParams['rows'] = $rows;
                }
                $oneHourRandom = floor(time() / 3600);
                $queryParams['sort'] = 'attr_' . $oneHourRandom . '_random asc';

                $result = SolrTool::rawSearch( $queryParams, 'php', false );
                if ( !isset( $result['response']['docs'] ) )
                {
                    eZDebug::writeError( 'Error from Solr for query : ' . $result['params']['fq'], __FILE__ . '::' . __LINE__ );
                    if( php_sapi_name() != 'cli' )
                    {
                        header( 'HTTP/1.x 500 Internal Server Error' );
                        eZExecution::cleanExit();
                    }
                }
            }

            $articles = $result['response']['docs'];

            // if mechanism 4, we need to have articles also from previous week
            if($applicationDictionaryRow["mechanism"] == 4)
            {
                $queryParams['fq'] = $queryParamsFqFallback;
                $queryParams['fq'][] = 'attr_online_date_dt:[NOW-14DAY TO NOW-7DAY]';
                $oneHourRandom = floor(time());
                $queryParams['sort'] = 'attr_' . $oneHourRandom . '_random asc';

                $queryParams['fq'] = implode( ' AND ', $queryParams['fq'] );
                $queryParams['rows'] = (int) $applicationDictionaryRow['number_article_random_y'];

                $resultRandom = SolrTool::rawSearch( $queryParams, 'php', false );
                if ( !isset( $resultRandom['response']['docs'] ) )
                {
                    eZDebug::writeError( 'Error from Solr for query : ' . $result['params']['fq'], __FILE__ . '::' . __LINE__ );
                    if( php_sapi_name() != 'cli' )
                    {
                        header( 'HTTP/1.x 500 Internal Server Error' );
                        eZExecution::cleanExit();
                    }
                }

                if(count($resultRandom['response']['docs'])) {
                    $articles = array_merge($articles, $resultRandom['response']['docs']);
                }
            }

            $this->_applicationsData[$applicationId][] = array(
                'articles'                    => $articles,
                'applicationDictionaryRow'    => $applicationDictionaryRow
            );
        }

        return $this->_applicationsData;
    }
    /**
     * @return string    fq parameter for the current configuration
     */
    public function getSolrFq()
    {
        $facets = eZINI::instance("merck.ini")->variable("ApplicationObjectSettings", "FacetMapping");
        $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByLocalizedId($this->attribute("application_localized_id"));
        $applicationFacets = array();
        if ( $applicationLocalized instanceof ApplicationLocalized ) {
            $applicationFacets = $applicationLocalized->applicationObject()->getContentServiceConfiguration()->getFacetList();
        }

        $mappingFacetClasses = array();
        /** @var ApplicationFacet $applicationFacet */
        foreach($applicationFacets as $applicationFacet)
        {
            $facetType = $applicationFacet->attribute("facet_type");
            if(isset($facets[$facetType]))
            {
                $mappingFacetClasses[$applicationFacet->attribute("attribute_identifier")] = $facets[$facetType];
            }
        }

        $finalFilters = array();
        $fq = $this->attribute("fq");

        if(!$fq || $fq == "")
        {
            return "";
        }

        $fields = json_decode($fq, true);
        if(!is_array($fields))
        {
            return null;
        }

        foreach($fields as $field => $values)
        {

            $filterOr = array();
            foreach($values as $value)
            {
                if($mappingFacetClasses[$field] && method_exists( $mappingFacetClasses[$field], 'getMapping' ))
                {
                    // special case when we have special value and not values like 201.1. Like for FacetPublisherSince
                    $className = $mappingFacetClasses[$field];
                    $mapping = $className::getMapping($field);

                    foreach($mapping as $data)
                    {
                        if($data["label"] == $value)
                        {
                            $filterOr[] = $data["query"];
                            break;
                        }
                    }
                }
                else if ($field == 'depth')
                {
                    $filterOr[] = sprintf('attr_relative_depth_i: %s', $value);
                }
                else
                {
                    $filterOr[] = sprintf('subattr_%s___source_id____s:"%s"', $field, $value);
                }
            }

            $finalFilters[] = '('.implode(" OR ", $filterOr).')';
        }
        $useDepth = $applicationLocalized->getCustomParameter('ShowParentArticleOnly');
        if (!$useDepth)
        {
            $useDepth = $applicationLocalized->applicationObject()->getCustomParameter('ShowParentArticleOnly');
        }
        if ($useDepth) {
            $finalFilters[] = 'attr_relative_depth_i: 0';
        }
        return implode(" AND ", $finalFilters);
    }
    /**
     * @param array $params
     * @return array
     */
    public static function rawSearch($params)
    {
        $localApplication = CacheApplicationTool::buildLocalizedApplicationByIdentifier(MerckManualShowcase::mainApplicationIdentifier());
        $publishersFilters = $localApplication->getPublishersFilter();
        
        if ( isset($params['fq']) && trim($params['fq']) != '' )
        {
            $params['fq'] .= ' AND ' . $publishersFilters;
        }
        else
        {
            $params['fq'] = $publishersFilters;
        }

        return SolrTool::rawSearch($params);
    }
    public static function initVars($year, $cluster, $auto)
    {
        if($auto)
        {
            self::$autoMode = true;
            self::$year = date('Y', strtotime('now'));
            self::$month = date('m', strtotime('now'));
            self::$batch = self::getBatchNumberFromToday();
        }
        else
        {
            self::$year = $year;
        }

        ClusterTool::setCurrentCluster($cluster);
        self::$tripApplication = CacheApplicationTool::buildLocalizedApplicationByIdentifier('trip');
        self::$tripIds = self::getAllTripLocalizedIds();

        $tab = FacetFilteringTool::getTaxonomyTranslation('customer_type');
        foreach($tab as $key => $val)
        {
            self::$customerTypeIds[] = $key;
        }
    }
    /**
     * @return int
     */
    public static function rootNodeId()
    {
        $merckManualAppLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( self::mainApplicationIdentifier() );
        $publisherNodeIds        = $merckManualAppLocalized->publisherNodeIds();
        $publisherNodeId         = $publisherNodeIds[0];

        return $publisherNodeId;
    }
    /**
     * @see ezfSolrDocumentFieldBase::getData()
     * @return array
     */
    public function getData()
    {
        $data           = parent::getData();
        $content        = $this->ContentObjectAttribute->content();
        
        /* @var $content array */
        foreach ( array_merge( self::taxonomyAttribute(), array_keys($content) ) as $taxonomyIdentifier )
        {
            $taxonomyValues              = isset( $content[$taxonomyIdentifier] ) ? $content[$taxonomyIdentifier] : array(); 
            $subattrSourceIdValues       = array();
            $subattrSourceIdFieldName    = self::getCustomSubattributeFieldName(
                                                $taxonomyIdentifier,
                                                'source_id');
            
            foreach ( $taxonomyValues as $taxonomyValue )
            {
                if( preg_match( '#^symptom_.*$#', $taxonomyValue ) )
                {
                    $sourceKey                  = $taxonomyValue;
                    $subattrSourceIdValues[]    = $sourceKey;
                    
                    // we need a few more things for the symptoms
                    /* @type $node eZContentObjectTreeNode */
                    $contentObject = $this->ContentObjectAttribute->object();
                    $node          = $contentObject->mainNode();
                    $clusters      = NodeTool::getArticleClusters($node);

                    foreach( $clusters as $cluster )
                    {
                        ClusterTool::setCurrentCluster($cluster);

                        $ini = eZINI::fetchFromFile('extension/'.$cluster.'/settings/site.ini');
                        $node->setCurrentLanguage( $ini->variable('RegionalSettings', 'ContentObjectLocale') );

                        $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( MerckManualShowcase::mainApplicationIdentifier() );
                        if ( !$applicationLocalized )
                            continue;

                        $customSymptomAttributeKey = 'attr_custom_symptom_'.$cluster.'_s';
                        $labelTranslations         = FacetFilteringTool::getTaxonomyTranslation( 'symptom' );
                        $label                     = $labelTranslations[$sourceKey];
                        $url                       = preg_replace( '#^[^/]+#', '', MerckManualFunctionCollection::getMerckManualNodeUrl( 'meck-manual-showcase', $node, $ini->variable('RegionalSettings', 'ContentObjectLocale') ) );

                        ClusterTool::resetCurrentCluster();

                        $customSymptomAttributeValueParts = array(
                            mb_strtolower(mb_substr(StringTool::removeAccents( StringTool::CJK2Pinyin($label) ), 0, 1)),
                            $label,
                            $url
                        );

                        $data[$customSymptomAttributeKey] = implode( '##', $customSymptomAttributeValueParts );
                    }
                }
                else if ( preg_match('#^222\.[0-9]+$#', $taxonomyValue ) )
                {
                    $sourceKey                  = $taxonomyValue;
                    $subattrSourceIdValues[]    = $sourceKey;

                    /* @type $node eZContentObjectTreeNode */
                    /* @type $dataMap eZContentObjectAttribute[] */
                    $contentObject                    = $this->ContentObjectAttribute->object();
                    $node                             = $contentObject->mainNode();
                    $clusters                         = NodeTool::getArticleClusters($node);
                    $customSymptomAttributeValueParts = array(
                        $content['layer_natom'][0],
                        $content['sub_layer_natom'][0],
                    );

                    foreach( $clusters as $cluster )
                    {
                        ClusterTool::setCurrentCluster($cluster);

                        $customSymptomAttributeKey        = 'attr_custom_layer_sublayer_natom_'.$cluster.'_s';
                        $data[$customSymptomAttributeKey] = implode( '##', $customSymptomAttributeValueParts );

                        ClusterTool::resetCurrentCluster();
                    }
                }
                else
                    $subattrSourceIdValues[] = trim( $taxonomyValue );
            }

            $data[$subattrSourceIdFieldName] = empty($subattrSourceIdValues) ? '' : $subattrSourceIdValues;
        }
        
        return $data;
    }
    /**
     * @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' )
                )
            );
        }
    }
    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 string $remote_id
     * @param string $cluster_identifier
     * @param string $description
     * @param string $url
     * @param string $application
     * @param string $elearningStatus
     * @return int
     */
    public static function addToMySelection( $remote_id, $cluster_identifier, $description, $url, $application, $elearningStatus = null )
    {
        $currentMMUser = MMUsers::getCurrentUserObject();

        if ( !($currentMMUser instanceof MMUsers) )
            return 0;

        $uuid = $currentMMUser->attribute( 'uuid' );
        $country = $currentMMUser->attribute( 'country' );

        if( !self::isAlreadyInUserSelection( $remote_id, $cluster_identifier ) )
        {
            if ( !$currentMMUser )
                return self::countTotalFromUserSelection();

            $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByApplication($application);
            $application = $applicationLocalized->applicationObject()->attribute('identifier');

            $selection = new MMSelections();
            $selection->setAttribute( 'uuid', $uuid );
            $selection->setAttribute( 'country', $country );
            $selection->setAttribute( 'url', $url );
            $selection->setAttribute( 'remote_id', $remote_id );
            $selection->setAttribute( 'cluster_identifier', $cluster_identifier );
            $selection->setAttribute( 'description', $description );
            $selection->setAttribute( 'add_date', time() );
            $selection->setAttribute( 'application', $application );

            $selection->store();
        }
        elseif( $application == 'e-learning' )
        {
            self::updateSelectionDescription( $remote_id, $cluster_identifier, $description, $elearningStatus );
        }

        self::setCookie();

        return self::countTotalFromUserSelection($uuid, $country);
    }
    /**
     * Return the right url of a node with application name and the node
     *
     * @param string $applicationName Identifier of the application
     * @param eZContentObjectTreeNode $node The article
     * @param string|boolean $languageCode
     *
     * @return null|string
     */
    public static function getUrlNode($applicationName, $node, $languageCode = false)
    {
        if ( !($node instanceof eZContentObjectTreeNode) )
            return null;

        $getUrlNodeHandlers = eZINI::instance( 'merck.ini' )->variable( 'OperatorsSettings', 'getUrlNodeHandlers' );

        if( isset( $getUrlNodeHandlers[$applicationName] ) )
        {
            $method = $getUrlNodeHandlers[$applicationName];
            return self::$method($applicationName, $node, $languageCode);
        }

        $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier($applicationName);

        if( !( $applicationLocalized instanceof ApplicationLocalized ) )
            return null;

        $applicationObject = $applicationLocalized->applicationObject;

        if( !( $applicationObject instanceof ApplicationObject ) )
            return null;

        $publisherFolderNodeId = PublisherFolderTool::getPublisherNodeIdFromArticleNode($node);

        if ( $publisherFolderNodeId == null )
            return null;

        if ( $languageCode )
            $node->setCurrentLanguage($languageCode);

        $forceExternalLink = $applicationObject->hasExternalLinkHandler();
        $publisherInfo     = PublisherFolderTool::getPublisherFolderInfosFromNodeId( $publisherFolderNodeId );
        $url               = preg_replace( '#^([^/]+/){2}#', '', $node->urlAlias() );

        return $applicationLocalized->applicationUrl( $forceExternalLink ) . "/{$publisherInfo['pfid']}/" . ltrim( $url, '/' );
    }
 /**
  * @param string $clusterId
  */
 public static function setCurrentCluster( $clusterId )
 {
     self::resetCurrentCluster();
     self::$_currentClusterId = $clusterId;
     CacheApplicationTool::flushMemoryCache();
 }
<?php
//header( 'Cache-Control: no-cache, must-revalidate' );
header('Content-Type', 'application/json');

$tpl = eZTemplate::factory();

$nodeID = $Params['NodeID'];
$applicationIdentifier = $Params['ApplicationIdentifier'];

$node = null;
if ($nodeID != null && $node != 'undefined')
{
    $node = eZContentObjectTreeNode::fetch($nodeID);
}

$application = CacheApplicationTool::buildLocalizedApplicationByApplication($applicationIdentifier);
if ($application instanceof ApplicationLocalized == false)
{
    echo json_encode(array(
        'publisher_logo' => false,
    ));
    return;
}


$publisherLogo = false;

$showRelatedPublishers = $application->applicationObject()->getCustomParameter('ShowPublisherLogos');

if ($showRelatedPublishers && $node != null && $node instanceof eZContentObjectTreeNode)
{
    /**
     * @param array $conditions
     * @return ApplicationObject[]
     */
    public static function fetchApplicationList ( $conditions = array() )
    {
        if( is_null(self::$_applicationList ) )
        {
            $appIds = parent::fetchObjectList(ApplicationObject::definition(), null, $conditions, null, null, false );
            $apps   = array();

            foreach( $appIds as $appId )
            {
                $appLocalized = CacheApplicationTool::buildLocalizedApplicationByApplication($appId['id']);

                if ( $appLocalized instanceof ApplicationLocalized && $appLocalized->applicationObject instanceof ApplicationObject )
                    $apps[] = $appLocalized->applicationObject;
            }
            self::$_applicationList = $apps;
        }

        return self::$_applicationList;
    }