/**
     * @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;
    }
    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;
     }
 }
    /**
     * @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;
    }
    /**
     * @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);
    }
    /**
     * @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' )
                )
            );
        }
    }
    /**
     * @return int
     */
    public static function rootNodeId()
    {
        $merckManualAppLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier( self::mainApplicationIdentifier() );
        $publisherNodeIds        = $merckManualAppLocalized->publisherNodeIds();
        $publisherNodeId         = $publisherNodeIds[0];

        return $publisherNodeId;
    }
    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;
        }
    }
Ejemplo n.º 10
0
    /**
     * @param array $uncrytedTicket
     * @return MMUsers
     */
    public static function createOrUpdateMMUser( $uncrytedTicket )
    {
        $userId = $uncrytedTicket['uuid'];
        $customerType = $uncrytedTicket['customerType'];
        if ( isset($uncrytedTicket['userSpeciality']) )
        {
            $userSpeciality = $uncrytedTicket['userSpeciality'];
        }
        else
        {
            $userSpeciality = $uncrytedTicket['mainSpeciality'];
        }
        $state = $uncrytedTicket['state'];
        $country = eZIni::instance('site.ini')->variable('RegionalSettings','CountryOfRegistration');
        $language = $uncrytedTicket['language'];
        /**
         * @todo: check $language entry format and parse it if needed to get an iso code on 2 chars
         */
        $iniMapping = eZINI::instance('mercktaxonomymapping.ini');
        $taxonomyType = $iniMapping->variable( 'Taxonomy', 'SpecialtiesTaxonomyType');

        $specialtiesMappingINI = $iniMapping->variable( 'Taxonomy', 'Specialties' );
        $customerTypesMappingINI = $iniMapping->variable( 'Taxonomy', 'CustomerTypes' );

        if($taxonomyType != "transitive")
        {
            if ( isset( $customerTypesMappingINI[$customerType] ) )
            {
                $customerType = $customerTypesMappingINI[$customerType];
            }
            else
            {
                $customerType = $customerTypesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-CT', $userId, $country );
            }

            if ( isset( $specialtiesMappingINI[$userSpeciality] ) )
            {
                $userSpeciality = $specialtiesMappingINI[$userSpeciality];
            }
            else
            {
                $userSpeciality = $specialtiesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-SPE', $userId, $country );
            }
        }
        else
        {
            $customerTypesMapping = SolrSafeOperatorHelper::getCustomerTypes();
            if ( !isset( $customerTypesMapping["$customerType"] ) )
            {
                // fill with default value
                $customerType = $customerTypesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-CT', $userId, $country );
            }

            $specialtiesMapping = SolrSafeOperatorHelper::getUserSpecialities();
            if ( !isset( $specialtiesMapping[(string)$userSpeciality] ) )
            {
                // fill with default value
                $userSpeciality = $specialtiesMappingINI['Default'];
                self::updateDBWithEmptyValue( 'empty-SPE', $userId, $country );
            }
        }

        /** @var MMUsers $user */
        $user = MMUsers::fetchByIdAndCountry( $userId, $country );
        $isModifiedUser = false;

        if ( $user )
        {
            if ( $customerType != $user->attribute('customer_type') )
            {
                $user->setAttribute('customer_type', $customerType);
                $isModifiedUser = true;
            }
            if ( $userSpeciality !== $user->attribute('user_speciality') )
            {
                $mainSpeciality = UserSpecialityContentSpeciality::getContentSpeciality ( $userSpeciality );
                $defaultAdditionalSpecialities = MMUserLogin::getAddSpecialties($mainSpeciality);

                $user->setAttribute('user_speciality', $userSpeciality);

                // mapping main_spe additional spe
                $preferences = $user->getPreferences();
                $userAditionalSpecialities = $preferences['specialities'];
                array_shift($userAditionalSpecialities);
                $tmp = array_diff( $userAditionalSpecialities, $defaultAdditionalSpecialities );
                if( empty( $tmp ) )    // we don't modify the user spes if he has changed his selection
                {
                    $preferences["specialities"] = MMUserLogin::getAddSpecialties($mainSpeciality);
                    $user->setPreferences($preferences);
                }
                $user->setPreferences($preferences);

                // The user specialty has been modified, we need to update it for Quiz-type applications of the current cluster
                if( CacheApplicationTool::buildLocalizedApplicationByIdentifier('train-the-brain') instanceof ApplicationLocalized)
                {
                    $playerScoring = QuizPlayerScoring::fetchOneBy( array( 'application_id' => (int)$app->applicationObject->id, 'uuid' => $user->attribute( 'uuid' ) ) );
                    // Checking if the current user has scored at least once for the application
                    if( $playerScoring )
                    {
                        foreach( FacetFilteringTool::getTaxoTranslationWithIDs( 'user_specialty' ) as $k => $t )
                        {
                            if( ($k . "") === ($userSpeciality . "") )
                            {
                                // Updating the user specialty id in the player scoring table
                                $playerScoring->setAttribute( 'user_specialty', $t['id'] );
                                $playerScoring->store();
                            }
                        }
                        // Scheduling a ranking update
                        QuizPendingRankingUpdate::add( $playerScoring->attribute( 'global_ranking' ), $app->applicationObject->id );
                    }
                }

                $isModifiedUser = true;
            }

            if ( $country != $user->attribute('country') )
            {
                $user->setAttribute('country', $country);
                $isModifiedUser = true;
            }

            if( $language != $user->attribute( 'language' ) )
            {
                $user->setAttribute('language', $language );
                $isModifiedUser = true;
            }

            if ( $state != $user->attribute('state') )
            {
                $user->setAttribute('state', $state);
                $isModifiedUser = true;
            }

            if ( $isModifiedUser )
            {
                $user->setAttribute('date_update', time());
                $user->store();
            }

            // set gpnotebook hand shake data in preferences
            if($user->getGPNotebookHS())
            {
                SolrSafeOperatorHelper::getAndStoreGPNotebookHS();
            }
        }
        else
        {
            $mainSpeciality = UserSpecialityContentSpeciality::getContentSpeciality ( $userSpeciality );
            $insertedArray = array (
                'uuid' => $userId,
                'customer_type' => $customerType,
                'user_speciality' => $userSpeciality,
                'country' => $country,
                'language' => $language,
                'date_update' => time(),
                'state' => $state,
            );

            $user = new MMUsers ($insertedArray);
            $user->store();

            // mapping main_spe additional spe
            $preferences = $user->getPreferences();
            $preferences["specialities"] = MMUserLogin::getAddSpecialties($mainSpeciality);
            $user->setPreferences($preferences);

            $isModifiedUser = true;
        }

        if ( $isModifiedUser )
        {
            // Tag Lyris user to be reimported :
            $user->tagLyrisToProcess();
        }

        return $user;
    }
    /**
     * 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, '/' );
    }
    public function login()
    {
        if ( !$this->_loginParams )
        {
            return $this->error();
        }

        $wsHelper = self::getWSHandler();
        $localizedLoginApplication = CacheApplicationTool::buildLocalizedApplicationByIdentifier( 'login' );
        $esbResult = new ESBResult();
        // Call the ESB Login webservice and populate the ESBResult object according to the ESB response

        $esbResponse = $wsHelper::call($this->_method, $this->_loginParams);
        static::populateESBResult($esbResult, $esbResponse);
        // UUMP autologin case
        if ( $this->_method == self::ESB_METHOD_READ )
            $esbResult->login = ( $esbResult->userId == $this->_input['userId'] );
        UserLog::instance()->step( 'esb' );

        $validationStatus = $esbResult->getValidationStatus();
        if ( $validationStatus == 'PV' && $localizedLoginApplication->getCustomParameter( 'RestrictPendingUsers' ) == 1 )
        {
            UserLog::instance()->esb_status('Pending')->store();
            $redirectURL = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'PendingUserStaticPage' );
            if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
            {
                $redirectURL = $redirectURL . '#?vs=PV';
            }
            $this->response($redirectURL);
        }
        elseif ( $validationStatus == 'RP' && $localizedLoginApplication->getCustomParameter( 'RestrictRejectedUsers' ) == 1 )
        {
            UserLog::instance()->esb_status('Rejected')->store();
            $redirectURL = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'RejectedUserStaticPage' );
            if( SolrSafeOperatorHelper::featureIsActive( 'GoogleAnalytics' ) )
            {
                $redirectURL = $redirectURL . '#?vs=RP';
            }
            $this->response($redirectURL);
        }
        elseif ( $esbResult->login )
        {
            $rememberMe = ( isset( $this->_input['rememberme'] ) && $this->_input['rememberme'] == 'on' );
            $context    = isset( $this->_input['context'] ) ? $this->_input['context'] : false;
            $username   = isset( $this->_input['LoginID'] ) ? $this->_input['LoginID'] : null;
            if ( isset( $this->_input['Username'] ) )
            {
                $username = $this->_input['Username'];
            }

            if ( !is_null( $esbResult->userName ) && $esbResult->userName != $username )
            {
                $username = $esbResult->userName;
            }

            if ( $this->_forceAutologin )
            {
                $esbResult->autologin = true;
            }

            // For compatibility with UUMP which do not need read call anymore
            if ( method_exists( get_class( $this ), "readCall" ) )
            {
                $isPopulated = static::populateESBResult( $esbResult, static::readCall( $username, $esbResult ) );

                if ( !$isPopulated )
                {
                    UserLog::instance()
                        ->uuid( $username )
                        ->esb_status( 'Error' )
                        ->msg('Read method call failed')
                        ->store();
                    // error log caught on WS stack
                    return $this->error();
                }
            }

            $this->_esbResult = $esbResult;

            $loginResult = MMUserLogin::esbLogin( $username, $esbResult, $rememberMe, $context );
        }

        if ( $loginResult )
        {
            $this->_isLoginSuccessful = true;

            UserLog::instance()
                ->uuid( $username )
                ->esb_status( 'Accepted' )
                ->store();

            $user = MMUsers::getCurrentUserObject();

            $sl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'esb_language' );
            $customerLanguage = !is_null( $sl ) ? $sl : eZINI::instance()->variable( 'RegionalSettings', 'ContentObjectLocale' );

            if( SolrSafeOperatorHelper::featureIsActive( 'AsynchronousAnalyticsLoginCall' ) && SolrSafeOperatorHelper::feature( 'AsynchronousAnalyticsLoginCall', 'GoogleAnalytics' ) )
            {
                $amq = new ActiveMQManager();
                $domains = eZINI::instance( 'merck.ini' )->variable( 'DomainMappingSettings', 'ClusterDomains' );
                $domain  = isset( $domains[ClusterTool::clusterIdentifier()] ) ? $domains[ClusterTool::clusterIdentifier()] : 'unidentified.univadis.com';
                $gasl = SystemLocale::fetchByClusterAndSystem( ClusterTool::clusterIdentifier(), 'ga_visitor_country' );
                $gaCountry = !is_null( $gasl ) ? $gasl : $user->attribute( 'country' );
                $gaParams = array(
                    'v'   => 1,
                    'tid' => 'UA-41415675-6',
                    'uid' => $user->attribute( 'uuid' ),
                    't'   => 'event',
                    'ec'  => 'esb',
                    'ea'  => 'login',
                    'ni'  => 1,
                    'cd1' => $user->attribute( 'uuid' ),
                    'cd2' => 'logged',
                    'cd7' => $gaCountry,
                    'dh'  => preg_replace( '#^.*?\.#', '', $domain ),
                );
                $gaParams = 'https://ssl.google-analytics.com/collect?' . http_build_query( $gaParams );
                $amq->sendMessageToQueue( 'portail.analytics.google', $gaParams );
            }

            $this->_destUrl = $loginResult['destUrl'];

            // Stringify params
            $loginResult['params'][AppBarControl::COOKIE_UNORDERED_APPLIST_KEY] = $user->getApplicationList();
            $loginResult['params'][MMUsers::COOKIE_KEY] = $user->getMMSettings();
            $cookieUserPreferences = MMUsers::getCookieUserPreferencesValues();
            foreach( $cookieUserPreferences as $key => $value )
            {
                $loginResult['params'][$key] = $value;
            }
            $strParams = json_encode( $loginResult['params'] );

            // Encrypts params
            $encryptedParams = MMUserLogin::encryptText( $strParams );
            // Redirect to PHP-ESI
            $redirectURL = "/loginActions.php?context=" . urlencode( $loginResult['destUrl'] ) . "&params=" . urlencode( $encryptedParams );

            $this->getSubsForOptin($user);

            // Branding reconsent check, done only if:
            // 1. feature ToUPPPopin enabled
            // 2. Always on WEB with this feature
            // 3. Only on mobile, whne setting showOnMobile is ON.
            if
            (
                SolrSafeOperatorHelper::featureIsActive( 'ToUPPPopin') 
                && 
                (
                    !ContextTool::instance()->isMobile()
                    ||
                    ( ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature('ToUPPPopin','showOnMobile') )
                )
            )
            {
                $displayReconsent = $this->checkTouPPPopin( $esbResponse );
                // if we need to ask user for reconsent ($displayReconsent - taken fromESB response) we decide if we want page below if:
                // 1. On WEB and useDedicatedPage setting is ON
                // 2. On mobile and useDedicatedPageMobile setting is ON
                if (
                    $displayReconsent
                    &&
                    (
                        ( !ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPage' ) )
                        ||
                        ( ContextTool::instance()->isMobile() && SolrSafeOperatorHelper::feature( 'ToUPPPopin', 'useDedicatedPageMobile' ) )
                    )
                )
                {
                    CookieTool::destroyCookie( 'displayToUPPPopin' );
                    CookieTool::destroyCookie( 'displayToUPPPopin', '/', null );
                    CookieTool::setCookie( 'displayToUPPPage', 1, time() + ( 2 * 24 * 60 * 60 ) );
                    $touPpPageUrl = eZINI::instance( 'site.ini' )->variable( 'SiteSettings', 'ToUPPPageUrl' ) . "/#?tpc=" . urlencode( $loginResult['destUrl'] );
                    $redirectURL = "/loginActions.php?context=" . urlencode( $touPpPageUrl ) . "&params=" . urlencode( $encryptedParams );
                }
            }
            // Consult Popin for France | mobile check disabled - it fails on STG
            if( /*ContextTool::instance()->isMobile() && */ in_array(ClusterTool::clusterIdentifier(), array( 'cluster_france' )))
            {
                CookieTool::destroyCookie('displayConsultMobile');
                CookieTool::destroyCookie('displayConsultMobile', '/', null);
                CookieTool::setCookie('displayConsultMobile', $user->getConsult(), time() + ( 2 * 24 * 60 * 60 ));
            }
            
            $this->response( $redirectURL );
        }
        elseif ( $esbResult->errorCode === 9 )
        {
            UserLog::instance()->esb_status( 'Error' )->msg( 'Error 9' )->store();

            if ( $this->_isAutologin && isset($this->_input['context']) )
            {
                $redirectURL = urldecode($this->_input['context']);
                $this->forceRedirect($redirectURL);
            }
            else
            {
                return $this->error( 1 );
            }
        }
        elseif ( !$esbResult->registered )
        {
            $errorMsg = $esbResult->msg;
            if ( empty($errorMsg) ) $errorMsg = 'Could not log user';
            UserLog::instance()->esb_status( 'Error' )->msg( $errorMsg )->store();

            if ( $this->_isAutologin && isset($this->_input['context']) )
            {
                $redirectURL = urldecode($this->_input['context']);
                $this->forceRedirect($redirectURL);
            }

            //#45436 REDIRECT TO COMUNITY PAGE AFTER BAD LOG-IN 
            if ( isset($this->_input['context']) && preg_match('/comuniti.fr/', $this->_input['context']) )
            {
                $redirectURL = urldecode($this->_input['context']);
                $redirectURL = substr( urldecode( parse_url($redirectURL, PHP_URL_QUERY) ),2 );
                $this->forceRedirect($redirectURL);
            }
            
            if ( $esbResult->errorCode > 0 && $esbResult->errorCode != 10 )
            {
                return $this->error( $esbResult->errorCode );
            }

            return $this->error( 3 );
        }

        UserLog::instance()
            ->step( 'after_login' )
            ->msg( 'Error: Unprocessed login for input: ' . print_r( $this->_input, true ) )
            ->store();

        return $this->error();
    }
    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 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 'timestampToDateISO':
                $operatorValue = date('c', $namedParameters['timestamp']);
                break;
            case 'ezstr_replace':
                $operatorValue = str_replace(
                    $namedParameters['search'],
                    $namedParameters['replace'],
                    $namedParameters['text']
                );
                break;
            case 'hash_set':
                $hash                          = $namedParameters['hash'];
                $hash[$namedParameters['key']] = $namedParameters['val'];
                $operatorValue                 = $hash;
                break;
            case 'currentApplication':
                $operatorValue = ApplicationDefault::instance();
                break;
            case 'getApplicationName':
                if ($namedParameters['application'] instanceof ApplicationDefault)
                {
                    $operatorValue = $namedParameters['application']->applicationName();
                }
                break;
            case 'getTableEmbeddedName':
                $pattern = '/<td class="MMTableCellHead" ?.*>(.*)<\/td>/';
                preg_match_all($pattern, $namedParameters['htmlCode'], $matches);

                $operatorValue = $matches[1][0];
                break;
            case 'external_app_cookie_key':
                $operatorValue = ExternalApplication::createExternalApplicationCookieKey(
                    $namedParameters['localized_application']
                );
                break;
            case 'getCurrentCluster':
                $operatorValue = ClusterTool::clusterIdentifier();
                break;
            case 'checkIfSiteMatchesType':
                $contexts = array(
                    ContextTool::APP_MOBILE_DESIGN,
                    ContextTool::FRONT_DESIGN,
                    ContextTool::MOBILE_DESIGN
                );

                $operatorValue = (in_array($namedParameters['site_type'], $contexts)) ? ContextTool::instance(
                )->siteIsTypeOf($namedParameters['site_type']) : false;
                break;
            case 'import_status_xml_mdd':
                $statusXmlMdd = array(
                    1 => 'COMPLETE_SUCCESS',
                    2 => 'SUCCESS_WITH_WARNINGS',
                    3 => 'BLOCKING_ERROR',
                    4 => 'CRITICAL_ERROR',
                    5 => 'FATAL_ERROR'
                );

                $operatorValue = (isset($statusXmlMdd[$namedParameters['status']]) ? $statusXmlMdd[$namedParameters['status']] : $namedParameters['status']);
                break;
            case 'import_status_mdd_ez':
                $statusMddEz = array(
                    '-1' => 'DO_NOT_TREAT',
                    0    => 'INITIAL',
                    1    => 'SYNCHRO',
                    2    => 'ARTICLE_REF',
                    4    => 'CRITICAL_ERROR',
                    8    => 'FATAL_ERROR'
                );

                $operatorValue = (isset($statusMddEz[$namedParameters['status']]) ? $statusMddEz[$namedParameters['status']] : $namedParameters['status']);
                break;
            case 'getUserCustomerType':
                $user          = MMUsers::getCurrentUserObject();
                $operatorValue = ($user) ? $user->attribute('customer_type') : 'User not logged in';
                break;
            case 'isUserDataMissing':
                $instance      = MMUserData::instance();
                $operatorValue = $instance->isUserDataMissing($namedParameters['name']);
                break;
            case 'isMobile':
                $operatorValue = ContextTool::instance()->isMobile();
                break;
            case 'getExternalConfiguration':
                $operatorValue = ApplicationExternalConfiguration::getExternalConfiguration($namedParameters['id']);
                break;
            case 'getLocalizedApplicationByIdentifier':
                $operatorValue = CacheApplicationTool::buildLocalizedApplicationByIdentifier(
                    $namedParameters['identifier']
                );
                break;
            case 'getWebtrendsTimezone':
                $d = new DateTime('now', new DateTimeZone(eZINI::instance()->variable('TimeZoneSettings', 'TimeZone')));

                $operatorValue = ($d->getOffset() / 3600);
                break;
            case 'getChinaProvinceCity':
                $operatorValue = ChinaLocation::fetchProvincesAndCities();
                break;
            case 'isCatchUpAppNameEnabled':
                $operatorValue = MMGlobalSearch::isCatchUpAppNameEnabled();
                break;
            case 'gmdate':
                $operatorValue = gmdate($namedParameters['format'], $namedParameters['duration']);
                break;
            case 'mb_strtoupper':
                $operatorValue = mb_strtoupper($namedParameters['str']);
                break;
            case 'preg_replace':
                $operatorValue = preg_replace(
                    $namedParameters['pattern'],
                    $namedParameters['replacement'],
                    $namedParameters['subject'],
                    $namedParameters['$limit']
                );
                break;
            case 'html_entity_decode':
                $operatorValue = html_entity_decode($namedParameters['string']);
                break;
            case 'urlencode':
                $operatorValue = urlencode($namedParameters['string']);
                break;
            case 'json_encode':
                $operatorValue = json_encode($namedParameters['value']);
                break;
            case 'domain':
                $operatorValue = ContextTool::instance()->domain();
                break;
            case 'getUumpDateFormat':
                $operatorValue = SolrSafeOperatorHelper::clusterIni('EsbDateConvert', 'FormatDate', 'merck.ini' );
                break;
            case 'html_contains_image':
                $operatorValue = SolrSafeOperatorHelper::htmlContainsImage($namedParameters['string']);
                break;
            case 'preg_match':
                $operatorValue = preg_match (
                    $namedParameters['pattern'],
                    $namedParameters['subject']
                );
                break;
        }
    }
Ejemplo n.º 15
0
<?php
	header( 'Cache-Control: no-cache, must-revalidate' );

	$globalSearchURi = CacheApplicationTool::buildLocalizedApplicationByIdentifier( 'global-search' )->attribute( 'url' );
	$globalSearch = ApplicationFactory::fetchByUri( $globalSearchURi );
	$globalSearch->initResultHandler();
	$resultHandler = $globalSearch->getResultHandler();

	$responseFormat = $Params['wt'];
	$keyword = trim( $Params['q'] );

	$filters = array();

	$filters[] = $resultHandler->publishersFilter();
	
	$additionalSolrFilters = $resultHandler->additionalSolrFilters();
	foreach($additionalSolrFilters as $a)
		$filters[] = $a;

    $params = array(
	    'indent'       => 'on',
	    'q'            => $keyword,
	    'fq'           => implode( ' AND ', $filters ),
	    'start'        => '',
	    'rows'         => '15',
	    'fl'           => 'attr_headline_s',
	    'qt'           => 'ezpublish',
	    'explainOther' => '',
	    'hl.fl'        => '',
	    'sort'         => 'score desc',
	);
 public function __construct()
 {
     $this->feedArticles = array();
     $this->application = CacheApplicationTool::buildLocalizedApplicationByIdentifier('bbc_feed');
 }
Ejemplo n.º 17
0
<?php

/* @type $Params string[] */

$appIdentifier = $Params['ApplicationIdentifier'];
$clusterIdentifier = isset( $Params['ClusterIdentifier'] ) ? $Params['ClusterIdentifier'] : ClusterTool::clusterIdentifier();

$varDir = eZINI::instance( 'site.ini' )->variable( 'FileSettings', 'VarDir' );
$outputFile =  "{$varDir}/images/common/apps/icon/{$appIdentifier}/{$clusterIdentifier}_ico.png";
$spriteImgPath = StaticData::clusterFilePath(false, "apps/{$appIdentifier}/ico_sprite.png");
$backgroundFilePath = './extension/ezoscar/design/oscar/images/common/appicon/background.png';

$fileUtils = eZClusterFileHandler::instance($outputFile);

ClusterTool::setCurrentCluster( $clusterIdentifier );
$app = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $appIdentifier );
ClusterTool::resetCurrentCluster();

if ( !$app instanceof ApplicationLocalized )
{
    eZDebug::writeError( "Application not found: {$appIdentifier}" );
    header('HTTP/1.0 404 Not Found');
    eZExecution::cleanExit();
}



if ( $fileUtils->fileExists( $outputFile ) )
{
    $appIcon = $fileUtils->fetchContents();
}
    /**
     * @param string $taxonomyCategory
     * @param float $taxonomyValue
     * @param int $limit
     * @param boolean $includeAllValues
     * @return array
     */
    public function getRelatedContent($taxonomyCategory, $taxonomyValue, $limit, $includeAllValues, $nodeId)
    {
        $fields = $this->mappingFieldsSolr;

        $filters = array();
        if ($includeAllValues)
        {
            foreach ($taxonomyValue as $tv)
            {
                $filters[] =  "subattr_{$taxonomyCategory}___source_id____s: \"{$tv}\"";
            }
        }
        else
        {
            $filter = "subattr_{$taxonomyCategory}___source_id____s: (%s)";
            $taxonomyValue = array_map( function($v) {
                return "\"{$v}\"";
            }, $taxonomyValue);
            $filter = sprintf($filter, implode(' OR ', $taxonomyValue));

            $filters[] = $filter;
        }

        $filters[] = '-meta_node_id_si: ' . $nodeId;
        $locale = LocaleTool::languageFromLocale();
        $filters[] = "meta_language_code_ms:".$locale.'*';

        $params = array(
            'indent'        => 'on',
            'q'             => '*:*',
            'fq'            => implode(' AND ' , $filters),
            'start'         => $this->offset,
            'rows'          => $limit,
            'fl'            => implode(',',$fields),
            'qt'            => 'ezpublish',
            'explainOther'  => '',
            'hl.fl'         => '',
            'sort'          => "attr_online_date_dt desc",
        );

        $solrResult =  SolrTool::rawSearch( $params, 'php', true, false );

        foreach ( $solrResult['response']['docs'] as $doc )
        {
            $nodeId                     = $doc['meta_node_id_si'][0];
            $articleNodeIDs[]           = $nodeId;
            $solrApplicationIndexes     = isset ( $doc[$fields['apps']] ) ? $doc[$fields['apps']] : array();
            $solrApplicationNames       = array();
            $solrApplicationIdentifiers = array();
            $app                        = null;

            foreach( $solrApplicationIndexes as $applicationIndex )
            {
                list ( $cluster, /* unused */, $applicationId ) = explode( '##', $applicationIndex );

                if ( $cluster == ClusterTool::clusterIdentifier() )
                {
                    $app = CacheApplicationTool::buildLocalizedApplicationByApplication( $applicationId );

                    if ( !($app instanceof ApplicationLocalized) )
                        continue;

                    $solrApplicationNames[] = $app->attribute('name');
                    $solrApplicationIdentifiers[] = $app->applicationObject()->attribute('identifier');
                }
            }

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

            if ( empty( $solrApplicationIdentifiers ) )
            {
                eZDebug::writeError( "Could not get application id for cluster for node $nodeId - Falling back to current application" );
                $solrApplicationIdentifiers = array( $this->contentList->applicationObject()->attribute('identifier') );
            }

            $masterApps = $this->contentList->iniMerck()->hasSection('MasterAppSettings') && $this->contentList->iniMerck()->hasVariable( 'MasterAppSettings', 'MasterAppList' )
                ? $this->contentList->iniMerck()->variable( 'MasterAppSettings', 'MasterAppList' )
                : array();

            $applicationIdentifier = $solrApplicationIdentifiers[0];

            if (!empty($masterApps))
            {
                foreach ($solrApplicationIdentifiers as $solrApplicationIdentifierKey => $solrApplicationIdentifier)
                {
                    if (in_array($solrApplicationIdentifier, $masterApps))
                    {
                        $applicationIdentifier = $solrApplicationIdentifier;
                        unset( $solrApplicationIdentifiers[$solrApplicationIdentifierKey] );
                        $solrApplicationIdentifiers = array_merge( array( $applicationIdentifier ), $solrApplicationIdentifiers );

                        break;
                    }
                }
            }

            $application       = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );
            $applicationObject = $application->applicationObject();
            $applicationType   = $applicationObject->applicationType()->attribute('type_identifier');
            $publisherPath     = $doc[$fields['publisher_path']][0];
            $publisherInfo     = PublisherFolderTool::getPathToIDMapping($publisherPath);
            $publisherFolderId = $publisherInfo['pfid'];
            $onlineDateStamp   = strtotime($doc[$fields['online_date']]) > 3600*24*2 ? SolrTool::getTimestampFromSolr($doc[$fields['online_date']]) : 0;
            $mediaTypes        = isset( $doc[$fields['media_types']] )
                ? json_decode( base64_decode($doc[$fields['media_types']]), true )
                : array();
            $mediaCount        = 0;
            $hasImage          = isset( $doc[$fields['has_image']] )
                ? json_decode( base64_decode($doc[$fields['has_image']]), true )
                : array();
            $url               = ($applicationType == 'first-child')
                ? $application->attribute('url_alias')
                : $application->attribute('url_alias') . '/' . $publisherFolderId . '/' . $url;

            $result[$nodeId] = array(
                'object_id'            => isset( $doc[$fields['object_id']] )            ? $doc[$fields['object_id']]            : null,
                'language'             => isset( $doc[$fields['language']] )             ? $doc[$fields['language']]             : null,
                'headline'             => isset( $doc[$fields['headline']] )             ? $doc[$fields['headline']]             : null,
                'promo_description'    => isset( $doc[$fields['promo_description']] )    ? $doc[$fields['promo_description']]    : null,
                'online_date'          => strtotime($doc[$fields['online_date']]) > 3600*24*2 ? SolrTool::getDateFromSolr($doc[$fields['online_date']]) : 0,
                'has_image'            => $hasImage,
                'url'                  => $url,
                'node_id'              => $nodeId,
                'internal_id'          => isset( $doc[$fields['internal_id']] )          ? $doc[$fields['internal_id']]            : null,
                'application'          => $application,
            );
        }
        return $result;
    }
Ejemplo n.º 19
0
    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 );
    }
    /**
     * 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]);
                }
            }
        }
    }
    /**
     * @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;
    }
Ejemplo n.º 22
0
    /**
     * @return array
     */
    public static function selectionList()
    {
        $userSelections = array();

        $selections = MMSelections::fetchUserSelection(null, null, false);

        /* @type $selection MMSelections */
        while ( list(, $selection) = each($selections) )
        {
            $object = eZContentObject::fetchByRemoteID($selection->attribute('remote_id'));
            if ( $object instanceof eZContentObject )
            {
                $node = $object->mainNode();
                /* @type $dataMap eZContentObjectAttribute[] */
                $dataMap = $node->dataMap();

                // Get first promo_image
                $image = false;
                if ( isset($dataMap['promo_image']) && $dataMap['promo_image']->hasContent() )
                {
                    $content = $dataMap['promo_image']->content();
                    $relationList = $content['relation_list'];
                    if ( isset($relationList[0]['node_id']) )
                    {
                        /* @type $imageDataMap eZContentObjectAttribute[] */
                        $imageNode = eZContentObjectTreeNode::fetch($relationList[0]['node_id']);
                        $imageDataMap = $imageNode->dataMap();
                        if ( isset($imageDataMap['file']) && $imageDataMap['file']->hasContent() )
                        {
                            /* @type $imageFileContent eZImageAliasHandler */
                            $imageFileContent = $imageDataMap['file']->content();
                            $imageFileAlias = $imageFileContent->imageAlias('original');
                            $image = $imageFileAlias['url'];
                        }
                    }
                }

                $applicationLocalized = CacheApplicationTool::buildLocalizedApplicationByIdentifier($selection->attribute('application'));
                $applicationObject = $applicationLocalized->applicationObject();

                $userSelections[] = array(
                    'headline'        => $node->getName(),
                    'nodeId'          => $selection->attribute('node_id'),
                    'date'            => date(DATE_ATOM, $selection->attribute('add_date')),
                    'application'     => $applicationObject->attribute('id'),
                    'applicationName' => $applicationLocalized->attribute("name"),
                    'description'     => $selection->attribute('description'),
                    'image'           => '/' . $image,
                    'url'             => NodeOperatorHelper::getUrlNode($selection->attribute('application'), $node)
                );
            }
        }

        return array(
            'selection' => $userSelections,
            'count'     => MMSelections::countTotalFromUserSelection()
        );
    }
    /**
     * @param string $type
     * @param int $offset
     * @param bool $includeAllFacets
     * @return array
     */
    protected function fetchUserLearningTracker( $type = null, $offset = 0, $includeAllFacets = false )
    {
        if( isset( $_POST['type'] ) && !is_null( $_POST['type'] ) && $_POST['type'] != 'null' )
        {
            $type = $_POST['type'];
        }
        if( isset( $_POST['offset'] ) && !is_null( $_POST['offset'] ) )
        {
            $offset = $_POST['offset'];
        }
        if( isset( $_POST['iaf'] ) && !is_null( $_POST['iaf'] ) && $_POST['iaf'] != 'false' )
        {
            $includeAllFacets = $_POST['iaf'];
        }
        
        $showResults = SolrSafeOperatorHelper::feature( 'MyLearningTracker', 'showResults' );
        $managedResults = $this->manageResults( $type, $offset, $includeAllFacets );
        if( $type == 'certificates' && $includeAllFacets )
        {
            $allManagedResults = $this->manageResults( null, 0, true );
            $managedResults['facetCounts'] = array_merge( $managedResults['facetCounts'], $allManagedResults['facetCounts'] );
            $managedResults['userCourses'] = $allManagedResults['userCourses'];
        }
        $this->tpl()->setVariable( 'items', $managedResults['items'] );
        $lineTemplate = 'design:esibuild/app_content/learning-tracker/line.tpl';
        if( $type == 'certificates' )
        {
            $this->tpl()->setVariable( 'current_localized', CacheApplicationTool::buildLocalizedApplicationByIdentifier( 'certificates' ) );
            $lineTemplate = 'design:esibuild/app_content/certificates/line.tpl';
        }
        $this->tpl()->setVariable( 'features', array(
            'line' => array('course-duration', 'credits', 'date', 'views', 'rating')
        ) );
        $this->tpl()->setVariable( 'is_learning_tracker', true );
        $this->tpl()->setVariable( 'cluster_identifier', ClusterTool::clusterIdentifier() );
        $articleResult = $this->tpl()->fetch( $lineTemplate );
        if( $includeAllFacets )
        {
            foreach( array( 'ongoing', 'planned', 'completed', 'certificates', 'passed' ) as $facetType )
            {
                if( !isset( $managedResults['facetCounts'][$facetType] ) )
                {
                    if($showResults && $facetType == 'completed'){
                        $managedResults['facetCounts'][$facetType] = intval($managedResults['facetCounts']['passed']) + intval($managedResults['facetCounts']['failed']);
                    }
                    else{
                        $managedResults['facetCounts'][$facetType] = 0;
                    }
                }
            }
        }

        return array(
            'content' => array(
                'articles'    => $articleResult,
                'articles_nb' => count( $managedResults['items'] ),
                'num_found'   => $managedResults['total'],
                'custom_f'    => $managedResults['facetCounts'],
                'userCourses' => $managedResults['userCourses'],
                'show_filter' => ( $type == 'completed' ? true : false ),
            )
        );
    }
    /**
     * @param array $solrResult
     * @param FacetBase[] $facets
     * @return array
     */
    public function articleResult(&$solrResult, $facets)
    {
        $returnArray     = array();
        $articleNodeIDs  = array();
        $articleSolrData = array();
        $articleData     = array();

        $fields = $this->getFields();

        foreach ( $solrResult['response']['docs'] as $doc )
        {
            $nodeId = $doc['meta_guid_ms'];
            $article = array(
                'headline'   => isset ( $doc[$fields['headline']] ) ? $doc[$fields['headline']] : array(),
                'url'        => isset ( $doc[$fields['url']] ) ? $doc[$fields['url']] : array(),
                'status'     => isset ( $doc[$fields['status']] ) ? $doc[$fields['status']] : array(),
                'condition'  => isset ( $doc[$fields['condition']] ) ? $doc[$fields['condition']] : array(),
                'gender'     => isset ( $doc[$fields['gender']] )  ? $doc[$fields['gender']] : array(),
                'min_age'    => isset ( $doc[$fields['min_age']] ) ? $doc[$fields['min_age']] : array(),
                'max_age'    => isset ( $doc[$fields['max_age']] ) ? $doc[$fields['max_age']] : array(),
                'country'    => isset ( $doc[$fields['country']] ) ? $doc[$fields['country']] : array(),
            );

            switch (reset($article['status']))
            {
                case '231.2': //                case ClinicalTrialsImportManager::STATUS_RECRUITING:
                    $article['status'] = 'RECRUITING';
                    break;
                case '231.1': //                case ClinicalTrialsImportManager::STATUS_NOT_RECRUITING:
                    $article['status'] = 'NOT RECRUITING';
                    break;
                default:
                    $article['status'] = 'NOT AVAILABLE';
                    break;

            }
            switch (count($article['gender']))
            {
                case 0:
                    $article['gender'] = 'NOT AVAILABLE';
                    break;
                case 1:
                    if ($article['gender'][0] == '')
                    {
                        $article['gender'] = 'NOT AVAILABLE';
                    }
                    else
                    {
                        $article['gender'] = 'GENDER_' . $article['gender'][0];
                    }
                    break;
                case 2:
                    $article['gender'] = 'GENDER_BOTH';
                    break;
            }
            if ($article['min_age'] == 0)
            {
                $article['min_age'] = 'NOT AVAILABLE';
            }
            if ($article['max_age'] == 0)
            {
                $article['max_age'] = 'NOT AVAILABLE';
            }

            $articleData[] = $article;

            $solrApplicationIndexes     = isset ( $doc[$fields['apps']] ) ? $doc[$fields['apps']] : array();
            $solrApplicationNames       = array();
            $solrApplicationIdentifiers = array();

            foreach( $solrApplicationIndexes as $applicationIndex )
            {
                list ( $cluster, $void, $applicationId ) = explode( '##', $applicationIndex );

                if ( $cluster == ClusterTool::clusterIdentifier() )
                {
                    $app = CacheApplicationTool::buildLocalizedApplicationByApplication( $applicationId );

                    if ( !($app instanceof ApplicationLocalized) )
                        continue;

                    $solrApplicationNames[] = $app->attribute('name');
                    $solrApplicationIdentifiers[] = $app->applicationObject()->attribute('identifier');
                }
            }

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

            if ( empty( $solrApplicationIdentifiers ) )
            {
                eZDebug::writeError( "Could not get application id for cluster for node $nodeId - Falling back to current application" );
                $solrApplicationIdentifiers = array( $this->contentList->applicationObject()->attribute('identifier') );
            }

            $masterApps = $this->contentList->iniMerck()->hasSection('MasterAppSettings') && $this->contentList->iniMerck()->hasVariable( 'MasterAppSettings', 'MasterAppList' )
                ? $this->contentList->iniMerck()->variable( 'MasterAppSettings', 'MasterAppList' )
                : array();

            $applicationIdentifier = $solrApplicationIdentifiers[0];

            if (!empty($masterApps))
            {
                foreach ($solrApplicationIdentifiers as $solrApplicationIdentifierKey => $solrApplicationIdentifier)
                {
                    if (in_array($solrApplicationIdentifier, $masterApps))
                    {

                        $applicationIdentifier = $solrApplicationIdentifier;
                        unset( $solrApplicationIdentifiers[$solrApplicationIdentifierKey] );
                        $solrApplicationIdentifiers = array_merge( array( $applicationIdentifier ), $solrApplicationIdentifiers );

                        break;
                    }
                }
            }

            $application       = CacheApplicationTool::buildLocalizedApplicationByIdentifier( $applicationIdentifier );
            $applicationObject = $application->applicationObject();
            $applicationType   = $applicationObject->applicationType()->attribute('type_identifier');
            $url               = ($applicationType == 'first-child') ? '/' . $application->attribute('url') : '/'.$application->attribute('url').'/'.$url;

            $articleSolrData[$nodeId] = array(
                'url'               => $url,
                'headline'          => isset( $doc[$fields['headline']] ) ? $doc[$fields['headline']] : null,
                'promo_description' => isset( $doc[$fields['promo_description']] ) ? $doc[$fields['promo_description']] : null,
                'apps'              => $solrApplicationNames,
                'app_identifiers'   => $solrApplicationIdentifiers,
                'trip_speciality'   => isset( $doc[$fields['trip_speciality']] ) ? $doc[$fields['trip_speciality']] : null,
                'trip_url'          => isset( $doc[$fields['trip_url']] ) ? $doc[$fields['trip_url']] : null,
                'trip_publication'  => isset( $doc[$fields['trip_publication']] ) ? $doc[$fields['trip_publication']] : null
            );
        }
        if( $this->withArticles )
        {
            $articleInformations = array(
                'articles'                      => $articleData,
                'articles_solrdata'             => $articleSolrData,
                'features'                      => $this->features,
                'with_feed'                     => $this->withFeed,
                'content_service_configuration' => ( isset($app) ? $app->applicationObject->configurationContentService : array() ),
            );

            $returnArray['article_informations'] = $articleInformations;
            $returnArray['articles_nb']          = count($articleNodeIDs);

            if( trim($this->searchQuery) != '' )
            {
                if( isset( $solrResult['spellcheck']['suggestions']) )
                    $returnArray['kw_suggestion'] = $solrResult['spellcheck']['suggestions']['collation'];
            }

            if( isset( $solrResult['highlighting'] ) )
            {
                $highlights = $this->parseSolrHighlights( $solrResult );

                if( $highlights )
                    $returnArray['highlights'] = $highlights;
            }
        }

        if ( $this->withAllSpecialities )
        {
            $facet = null;

            foreach($this->contentList->facets as $f)
            {
                if( $f instanceof FacetFieldTagSpeciality )
                {
                    $facet = $facets[$f->key]['list'];
                    break;
                }
            }

            $main_speciality = '';
            $specialities    = array();
            $first           = true;

            foreach( $facet as $lbl => $arr )
            {
                if( $first )
                {
                    $main_speciality = $lbl;
                    $first           = false;
                }
                else
                    $specialities[$lbl] = $arr;
            }

            $allSpecialitiesInformations = array(
                'main_speciality'  => $main_speciality,
                'specialities'     => $specialities,
                'all_specialities' => $this->allSpecialitiesFacet()
            );

            $returnArray['all_specialities_informations'] = $allSpecialitiesInformations;
        }

        if( $this->withMostPopularKeywords )
            $returnArray['most_popular_kw'] = $this->keywordsAutocomplete('');

        if ( $this->withT3Facets )
        {
            $t3FacetInformations = array();

            foreach($this->contentList->facets as $index => $f)
            {
                if( $f instanceof FacetFieldTagType3 )
                {
                    $t3FacetInformations['t3_facets'] = $facets[$f->key]['list'];
                    $t3FacetInformations['t3_name'] = $f->key;
                    $t3FacetInformations['t3_key'] = 'f'.$index;
                    break;
                }
            }

            $returnArray['t3_facet_informations'] = $t3FacetInformations;
        }
        return $returnArray;
    }