/**
     * @param int $uxType
     * @param string $key
     * @param string $field
     */
    public function __construct($uxType, $key, $field)
    {
        parent::__construct($uxType, $key, $field);

        $this->canBeHidden     = true;
        $this->hideEmptyValues = false;

        if ( self::isForcedLanguage() )
        {
            $this->forcedValues = array( LocaleTool::languageISO639Code(LocaleTool::mainLanguage()) );
        }

        $defaultValues = array( LocaleTool::languageISO639Code() );
        foreach( LocaleTool::languageList() as $locale )
        {
            $language = LocaleTool::languageISO639Code( $locale );
            if( !isset($defaultValues[$language]) )
                $defaultValues[] = $language;
        }

        $this->defaultValues = $defaultValues;

        $overrideLanguageFacetIsActive = SolrSafeOperatorHelper::featureIsActive('DefaultLanguageFacetValues');
        if ($overrideLanguageFacetIsActive)
        {
            $forcedLanguageOverrides = SolrSafeOperatorHelper::feature('DefaultLanguageFacetValues', 'ApplicationDefaultLanguage');
            if (!empty($forcedLanguageOverrides))
            {
                $identifier = self::$applicationIdentifier;

                if (!empty($identifier) && isset($forcedLanguageOverrides[$identifier]))
                {
                    $this->forcedValues = $forcedLanguageOverrides[$identifier];
                }
            }
        }
    }
    /**
     * @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' )
                )
            );
        }
    }
    /**
     * @param resource $curlXMLResponse
     * @return array
     */
    protected function processXML($curlXMLResponse)
    {
        //delete existing nodes
        try
        {
            echo "Deleting Previous articles\n";
            $this->deletePreviousArticles();
        }
        catch (Exception $e)
        {
            return null;
        }

        $xml = simplexml_load_string($curlXMLResponse,  null, LIBXML_NOCDATA);
        $xmlArray = json_decode(json_encode($xml), true);

        $i = 0;
        $formattedArticles = array();

        if(isset($xmlArray['channel']))
        {
            if(isset($xmlArray['channel']['item']) && !empty($xmlArray['channel']['item']))
            {
                if(!isset($xmlArray['channel']['item'][0]))
                {
                    $xmlArray['channel']['item'] = array($xmlArray['channel']['item']);
                }

                foreach($xmlArray['channel']['item'] as $article)
                {
                    if($i < 3)
                    {
                        try
                        {
                            $formattedArticle = array(
                                'meta_installation_id_ms'           => keZSolr::installationID(),
                                'meta_guid_ms'                      => md5($article['link'] . $article['category']),
                                'meta_section_id_si'                => 1,
                                'attr_' . ClusterTool::clusterIdentifier() . '_url_s' => $article['link'],
                                'attr_date_dt'                      => $this->formatDate(DATE_RFC2822, $article['pubDate'], "Y-m-d\TH:i:s\Z"),
                                'attr_offline_date_dt'              => '1970-01-01T01:00:00Z',
                                'attr_archive_date_dt'	            => '1970-01-01T01:00:00Z',
                                'attr_headline_t'                   => $article['title'],
                                'attr_headline_lc_s'                => strtolower($article['title']),
                                'attr_promo_description_t'          => empty($article['description']) ? '' : $article['description'],
                                'attr_category_t'                   => empty($article['category']) ? '' : $article['category'],
                                'attr_is_invisible_' . ClusterTool::clusterIdentifier() . '_b'    => false,
                                'subattr_language___source_id____s' => $xmlArray['channel']['language'],
                                'subattr_language_' . ClusterTool::clusterIdentifier() . '____s'              => $xmlArray['channel']['language'],
                                'subattr_publisher_folder___source_id____s'	    => 'congress_report_pt',
                                'meta_language_code_ms'             => LocaleTool::mainLanguage(),
                                'meta_class_identifier_ms'          => 'article',
                                'attr_relative_depth_i'             => 0,
                            );
                            $formattedArticles[] = json_encode($formattedArticle);
                        }
                        catch(Exception $e)
                        {
                            echo "\n Error with item : " , $article['title'] , ' : ' , $e->getMessage() , "\n";
                            continue;
                        }

                        $i++;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        echo "|-- $i articles found.\n";
        $this->totalProcessed += $i;

        return $formattedArticles;
    }
    /**
     * @param $curlXMLResponse
     * @return array
     */
    function processXML($curlXMLResponse)
    {
        $xml = simplexml_load_string($curlXMLResponse,  null, LIBXML_NOCDATA);
        $xmlArray = json_decode(json_encode($xml), true);

        $i = 0;
        $formattedArticles = array();

        if(isset($xmlArray['channel']))
        {
            if(isset($xmlArray['channel']['item']) && !empty($xmlArray['channel']['item']))
            {
                if(!isset($xmlArray['channel']['item'][0]))
                {
                    $xmlArray['channel']['item'] = array($xmlArray['channel']['item']);
                }

                foreach($xmlArray['channel']['item'] as $article)
                {
                    try
                    {
                        if( !isset($article['dateStart']) || !$article['dateStart'] )
                        {
                            $article['dateStart'] = $this->formatDate('d-m-Y H:i:s O', $article['pubDate'], "Y-m-d\TH:i:s\Z");
                        }
                        if(  !isset($article['dateEnd']) || !$article['dateEnd'] )
                        {
                            $article['dateEnd'] = $this->formatDate('d-m-Y H:i:s O', $article['pubDate'], "Y-m-d\TH:i:s\Z");
                        }

                        $formattedArticle = array(
                            'meta_installation_id_ms'           => keZSolr::installationID(),
                            'meta_path_si'                      => $this->getMetaPathId(),
                            'meta_guid_ms'                      => md5($this->applicationIdentifier . $article['guid']. $article['link']),
                            'meta_remote_id_ms'                 => md5($this->applicationIdentifier . $article['guid']. $article['link']),
                            'meta_section_id_si'                => 1,
                            'attr_' . ClusterTool::clusterIdentifier() . '_url_s' => md5($this->applicationIdentifier . $article['guid']. $article['link']),
                            'attr_date_dt'                      => $this->formatDate('d-m-Y H:i:s O', $article['pubDate'], "Y-m-d\TH:i:s\Z"),
                            //'attr_article_date_dt'              => $this->formatDate('d-m-Y H:i:s', $article['pubDate'], "Y-m-d\TH:i:s\Z"),
                            //'attr_article_year_i'               => $this->formatDate('d-m-Y H:i:s', $article['pubDate'], "Y"),
                            //'attr_article_month_i'              => $this->formatDate('d-m-Y H:i:s', $article['pubDate'], "m"),
                            'attr_date_start_dt'                => $this->formatDate('d-m-Y H:i:s', $article['dateStart'], "Y-m-d\TH:i:s\Z"),
                            'attr_article_year_start_i'         => $this->formatDate('d-m-Y H:i:s', $article['dateStart'], "Y"),
                            'attr_article_month_start_i'        => $this->formatDate('d-m-Y H:i:s', $article['dateStart'], "m"),
                            'attr_date_end_dt'                  => $this->formatDate('d-m-Y H:i:s', $article['dateEnd'], "Y-m-d\TH:i:s\Z"),
                            'attr_article_year_end_i'           => $this->formatDate('d-m-Y H:i:s', $article['dateEnd'], "Y"),
                            'attr_article_month_end_i'          => $this->formatDate('d-m-Y H:i:s', $article['dateEnd'], "m"),
                            'attr_offline_date_dt'              => '1970-01-01T01:00:00Z',
                            'attr_archive_date_dt'	            => '1970-01-01T01:00:00Z',
                            'attr_headline_t'                   => $article['title'],
                            'attr_headline_s'                   => $article['title'],
                            'attr_headline_lc_s'                => strtolower($article['title']),
                            'attr_promo_description_t'          => empty($article['description']) ? '' : $article['description'],
                            'attr_is_invisible_' . ClusterTool::clusterIdentifier() . '_b'    => false,
                            'subattr_speciality___source_id____s'        => $this->specialityIds,
                            'subattr_language___source_id____s'             => $xmlArray['channel']['language'],
                            'subattr_language_' . ClusterTool::clusterIdentifier() . '____s'              => $xmlArray['channel']['language'],
                            'subattr_local_application___source_id____s'    => $this->application->application_id,
                            'subattr_local_application___source_mixed____s' => $this->getAllApplicationLocalizedIds(),
                            'subattr_publisher_folder___source_id____s'	    => $this->getPublisherFolderPath(),
                            'meta_language_code_ms'     => LocaleTool::mainLanguage(),
                            'meta_class_identifier_ms' => 'article',
                            'attr_content_rating_'. ClusterTool::clusterIdentifier() .'_f'  =>  0,
                            'attr_view_counter_'. ClusterTool::clusterIdentifier() .'_i'    =>  0,
                            'attr_evrika_address_city_s'         => trim($article['address']),
                            'subattr_evrika_specialty____s'          => array_map(function($item) { return trim($item); }, array_filter(explode(';', $article['specialties']), function($item) { return strlen(trim($item)) > 0; })),
                            'attr_evrika_address_city_t_ru'      => trim($article['address']),
                        );
                        $formattedArticles[] = json_encode($formattedArticle);
                        $i++;
                    }
                    catch(Exception $e)
                    {
                        echo "\n Error with item guid : " , $article['guid'] , ' : ' , $e->getMessage() , "\n";
                        continue;
                    }
                }
            }
        }

        echo "|-- $i articles found.\n";
        $this->totalProcessed += $i;

        return $formattedArticles;
    }