Exemplo n.º 1
0
 public function attribute($key)
 {
     switch ($key) {
         case 'start_timestamp':
             return $this->start->format('U');
             break;
         case 'start_js':
             return $this->start->format('U') * 1000;
             break;
         case 'start_solr':
             return ezfSolrDocumentFieldBase::preProcessValue($this->start->format('U'), 'date');
             break;
         case 'end_timestamp':
             return $this->end->format('U');
             break;
         case 'end_js':
             return $this->end->format('U') * 1000;
             break;
         case 'end_solr':
             return ezfSolrDocumentFieldBase::preProcessValue($this->end->format('U'), 'date');
             break;
         default:
             return false;
     }
 }
Exemplo n.º 2
0
 /**
  * Search on the Solr search server
  *
  * @param string search term
  * @param array parameters.
  *      Example:
  * <code>
  * array( 'SearchOffset' => <offset>,
  *        'SearchLimit' => <limit>,
  *        'SearchSubTreeArray' => array( <node ID1>[, <node ID2>]... ),
  *        'SearchContentClassID' => array( <class ID1>[, <class ID2>]... ),
  *        'SearchContentClassAttributeID' => <class attribute ID>,
  *        'Facet' => array( array( 'field' => <class identifier>/<attribute identifier>[/<option>], ... ) ) ),
  *        'Filter' => array( <base_name> => <value>, <base_name2> => <value2> ),
  *        'SortBy' => array( <field> => <asc|desc> [, <field2> => <asc|desc> [,...]] ) |
  *                    array( array( <field> => <asc|desc> )[, array( <field2> => <asc|desc> )[,...]] ),
  *        'BoostFunctions' => array( 'fields' => array(
  *                                               'article/title' => 2,
  *                                               'modified:5'
  *                                                    ),
  *                                   'functions' => array( 'rord(meta_modified_dt)^10' )
  *                                  ),
  *        'ForceElevation' => false,
  *        'EnableElevation' => true
  *        'DistributedSearch" => array ( 'shards', array( 'shard1', 'shard2' , ... )
  *                                        'searchfields', array ( 'myfield1, 'myfield2', ... )
  *                                        'returnfields', array ( 'myfield1, 'myfield2', ... )
  *                                        'rawfilterlist, array ( 'foreignfield:a', '(foreignfield:b AND otherfield:c)', ... )
  *                                      )
  *      );
  * </code>
  * For full facet description, see facets design document.
  * For full description about 'ForceElevation', see elevate support design document ( elevate_support.rst.txt )
  *
  * the rawFilterList in distributed search is appended to the policyfilterlist with an 'OR' for each entry, as the policy list will
  * in general not be applicable to foreign indexes. To be used with care!
  *
  * @param array Search types. Reserved.
  *
  * @return array Solr query results.
  *
  * @see ezfeZPSolrQueryBuilder::buildBoostFunctions()
  */
 public function buildSearch($searchText, $params = array(), $searchTypes = array())
 {
     eZDebugSetting::writeDebug('extension-ezfind-query', $params, 'search params');
     $searchCount = 0;
     $eZFindIni = eZINI::instance('ezfind.ini');
     $solrIni = eZINI::instance('solr.ini');
     $siteIni = eZINI::instance('site.ini');
     $offset = isset($params['SearchOffset']) ? $params['SearchOffset'] : 0;
     $limit = isset($params['SearchLimit']) ? $params['SearchLimit'] : 10;
     $subtrees = isset($params['SearchSubTreeArray']) ? $params['SearchSubTreeArray'] : array();
     $contentClassID = isset($params['SearchContentClassID']) && $params['SearchContentClassID'] != -1 ? $params['SearchContentClassID'] : false;
     $contentClassAttributeID = isset($params['SearchContentClassAttributeID']) && $params['SearchContentClassAttributeID'] != -1 ? $params['SearchContentClassAttributeID'] : false;
     $sectionID = isset($params['SearchSectionID']) && $params['SearchSectionID'] > 0 ? $params['SearchSectionID'] : false;
     $dateFilter = isset($params['SearchDate']) && $params['SearchDate'] > 0 ? $params['SearchDate'] : false;
     $asObjects = isset($params['AsObjects']) ? $params['AsObjects'] : true;
     $spellCheck = isset($params['SpellCheck']) && $params['SpellCheck'] > 0 ? $params['SpellCheck'] : array();
     $queryHandler = isset($params['QueryHandler']) ? $params['QueryHandler'] : $eZFindIni->variable('SearchHandler', 'DefaultSearchHandler');
     // eZFInd 2.3: check ini setting and take it as a default instead of false
     $visibilityDefaultSetting = $siteIni->variable('SiteAccessSettings', 'ShowHiddenNodes');
     $visibilityDefault = $visibilityDefaultSetting === 'true' ? true : false;
     $ignoreVisibility = isset($params['IgnoreVisibility']) ? $params['IgnoreVisibility'] : $visibilityDefault;
     $this->searchPluginInstance->postSearchProcessingData['ignore_visibility'] = $ignoreVisibility;
     $limitation = isset($params['Limitation']) ? $params['Limitation'] : null;
     $boostFunctions = isset($params['BoostFunctions']) ? $params['BoostFunctions'] : null;
     $forceElevation = isset($params['ForceElevation']) ? $params['ForceElevation'] : false;
     $enableElevation = isset($params['EnableElevation']) ? $params['EnableElevation'] : true;
     $distributedSearch = isset($params['DistributedSearch']) ? $params['DistributedSearch'] : false;
     $fieldsToReturn = isset($params['FieldsToReturn']) ? $params['FieldsToReturn'] : array();
     $highlightParams = isset($params['HighLightParams']) ? $params['HighLightParams'] : array();
     $searchResultClusterParams = isset($params['SearchResultClustering']) ? $params['SearchResultClustering'] : array();
     $extendedAttributeFilter = isset($params['ExtendedAttributeFilter']) ? $params['ExtendedAttributeFilter'] : array();
     // distributed search option
     // @since ezfind 2.2
     $extraFieldsToSearch = array();
     $extraFieldsToReturn = array();
     $shardURLs = array();
     $iniShards = $solrIni->variable('SolrBase', 'Shards');
     $shardQuery = NULL;
     $shardFilterQuery = array();
     if (isset($distributedSearch['shards'])) {
         foreach ($distributedSearch['shards'] as $shard) {
             $shardURLs[] = $iniShards[$shard];
         }
         $shardQuery = implode(',', $shardURLs);
     }
     if (isset($distributedSearch['searchfields'])) {
         $extraFieldsToSearch = $distributedSearch['searchfields'];
     }
     if (isset($distributedSearch['returnfields'])) {
         $extraFieldsToReturn = $distributedSearch['returnfields'];
     }
     if (isset($distributedSearch['rawfilterlist'])) {
         $shardFilterQuery = $distributedSearch['rawfilterlist'];
     }
     // check if filter parameter is indeed an array, and set it otherwise
     if (isset($params['Filter']) && !is_array($params['Filter'])) {
         $params['Filter'] = array($params['Filter']);
     }
     $pathFieldName = eZSolr::getMetaFieldName($ignoreVisibility ? 'path' : 'visible_path');
     $filterQuery = array();
     // Add subtree query filter
     if (!empty($subtrees)) {
         $this->searchPluginInstance->postSearchProcessingData['subtree_array'] = $subtrees;
         $subtreeQueryParts = array();
         foreach ($subtrees as $subtreeNodeID) {
             $subtreeQueryParts[] = $pathFieldName . ':' . $subtreeNodeID;
         }
         $filterQuery[] = implode(' OR ', $subtreeQueryParts);
     }
     // Add policy limitation query filter
     $policyLimitationFilterQuery = $this->policyLimitationFilterQuery($limitation, $ignoreVisibility);
     if ($policyLimitationFilterQuery !== false) {
         $filterQuery[] = $policyLimitationFilterQuery;
     }
     // Add time/date query filter
     if ($dateFilter > 0) {
         switch ($dateFilter) {
             // last day
             case 1:
                 $searchTimestamp = strtotime('-1 day');
                 break;
                 // last week
             // last week
             case 2:
                 $searchTimestamp = strtotime('-1 week');
                 break;
                 // last month
             // last month
             case 3:
                 $searchTimestamp = strtotime('-1 month');
                 break;
                 // last three month
             // last three month
             case 4:
                 $searchTimestamp = strtotime('-3 month');
                 break;
                 // last year
             // last year
             case 5:
                 $searchTimestamp = strtotime('-1 year');
                 break;
         }
         $filterQuery[] = eZSolr::getMetaFieldName('published') . ':[' . ezfSolrDocumentFieldBase::preProcessValue($searchTimestamp, 'date') . '/DAY TO *]';
     }
     if ((!eZContentObjectTreeNode::showInvisibleNodes() || !$ignoreVisibility) && $eZFindIni->variable('SearchFilters', 'FilterHiddenFromDB') == 'enabled') {
         $db = eZDB::instance();
         $invisibleNodeIDArray = $db->arrayQuery('SELECT node_id FROM ezcontentobject_tree WHERE ezcontentobject_tree.is_invisible = 1', array('column' => 0));
         $hiddenNodesQueryText = 'meta_main_node_id_si:[* TO *] -meta_main_node_id_si:(';
         foreach ($invisibleNodeIDArray as $element) {
             $hiddenNodesQueryText = $hiddenNodesQueryText . $element['node_id'] . ' ';
         }
         $hiddenNodesQueryText = $hiddenNodesQueryText . ')';
         // only add filter if there are hidden nodes after all
         if ($invisibleNodeIDArray) {
             $filterQuery[] = $hiddenNodesQueryText;
         }
     }
     // Add content class query filter
     $classLimitationFilter = $this->getContentClassFilterQuery($contentClassID);
     if ($classLimitationFilter !== null) {
         $filterQuery[] = $classLimitationFilter;
     }
     // Add section to query filter.
     if ($sectionID) {
         $filterQuery[] = eZSolr::getMetaFieldName('section_id') . ':' . $sectionID;
     }
     $languageFilterQuery = $this->buildLanguageFilterQuery();
     if ($languageFilterQuery) {
         $filterQuery[] = $languageFilterQuery;
     }
     $paramFilterQuery = $this->getParamFilterQuery($params);
     if (!empty($paramFilterQuery)) {
         $filterQuery = array_merge($filterQuery, $paramFilterQuery);
     }
     //add raw filters
     if ($eZFindIni->hasVariable('SearchFilters', 'RawFilterList')) {
         $rawFilters = $eZFindIni->variable('SearchFilters', 'RawFilterList');
         if (is_array($rawFilters)) {
             $filterQuery = array_merge($filterQuery, $rawFilters);
         }
     }
     // Build and get facet query prameters.
     $facetQueryParamList = $this->buildFacetQueryParamList($params);
     // search only text type declared fields
     $fieldTypeExcludeList = $this->fieldTypeExludeList(NULL);
     // Create sort parameters based on the parameters.
     $sortParameter = $this->buildSortParameter($params);
     //the array_unique below is necessary because attribute identifiers are not unique .. and we get as
     //much highlight snippets as there are duplicate attribute identifiers
     //these are also in the list of query fields (dismax, ezpublish) request handlers
     $queryFields = array_unique($this->getClassAttributes($contentClassID, $contentClassAttributeID, $fieldTypeExcludeList));
     //highlighting only in the attributes, otherwise the object name is repeated in the highlight, which is already
     //partly true as it is mostly composed of one or more attributes.
     //maybe we should add meta data to the index to filter them out.
     $highLightFields = $queryFields;
     //@since eZ Find 2.3
     //when dedicated attributes are searched for, don't add meta-fields to the $queryfields list
     if (!$contentClassAttributeID) {
         $queryFields[] = eZSolr::getMetaFieldName('name');
         if (!$eZFindIni->hasVariable('SearchFilters', 'ExcludeOwnerName') || $eZFindIni->variable('SearchFilters', 'ExcludeOwnerName') !== 'enabled') {
             $queryFields[] = eZSolr::getMetaFieldName('owner_name');
         }
     }
     $spellCheckParamList = array();
     // @param $spellCheck expects array (true|false, dictionary identifier, ...)
     if (isset($spellCheck[0]) and $spellCheck[0] or $eZFindIni->variable('SpellCheck', 'SpellCheck') == 'enabled' and (isset($spellCheck[0]) and !$spellCheck[0])) {
         $dictionary = isset($spellCheck[1]) ? $spellCheck[1] : $eZFindIni->variable('SpellCheck', 'DefaultDictionary');
         $spellCheckParamList = array('spellcheck' => 'true', 'spellcheck.q' => $searchText, 'spellcheck.dictionary' => $dictionary, 'spellcheck.collate' => 'true', 'spellcheck.extendedResults' => 'true', 'spellcheck.onlyMorePopular' => 'true', 'spellcheck.count' => 1);
     }
     // Create the Elevate-related parameters here :
     $elevateParamList = eZFindElevateConfiguration::getRuntimeQueryParameters($forceElevation, $enableElevation, $searchText);
     // process query handler: standard, simplestandard, ezpublish, heuristic
     // first determine which implemented handler to use when heuristic is specified
     if (strtolower($queryHandler) === 'heuristic') {
         // @todo: this code will evolve of course
         if (preg_match('/[\\^\\*\\~]|AND|OR/', $searchText) > 0) {
             $queryHandler = 'simplestandard';
         } else {
             $queryHandler = 'ezpublish';
         }
     }
     $handlerParameters = array();
     $queryHandler = strtolower($queryHandler);
     switch ($queryHandler) {
         case 'standard':
             // @todo: this is more complicated
             // build the query against all "text" like fields
             // should take into account all the filter fields and class filters to shorten the query
             // need to build: Solr q
             if (array_key_exists('fields', $boostFunctions)) {
                 $handlerParameters = array('q' => $this->buildMultiFieldQuery($searchText, array_merge($queryFields, $extraFieldsToSearch), $boostFunctions['fields']), 'qt' => 'standard');
             } else {
                 $handlerParameters = array('q' => $this->buildMultiFieldQuery($searchText, array_merge($queryFields, $extraFieldsToSearch)), 'qt' => 'standard');
             }
             break;
         case 'simplestandard':
             // not to do much, searching is against the default aggregated field
             // only highlightfields
             $highLightFields = array('ezf_df_text');
             $handlerParameters = array('q' => $searchText, 'qt' => 'standard', 'hl.usePhraseHighlighter' => 'true', 'hl.highlightMultiTerm' => 'true');
             break;
         case 'ezpublish':
             // the dismax based handler, just keywordss input, most useful for ordinary queries by users
             // need to build: Solr q, qf, dismax specific parameters
         // the dismax based handler, just keywordss input, most useful for ordinary queries by users
         // need to build: Solr q, qf, dismax specific parameters
         default:
             // ezpublish of course, this to not break BC and is the most "general"
             // if another value is specified, it is supposed to be a dismax like handler
             // with possible other tuning variables then the stock provided 'ezpublish' in solrconfi.xml
             // remark it should be lowercase in solrconfig.xml!
             $boostQueryString = $this->boostQuery();
             $rawBoostQueries = $eZFindIni->variable('QueryBoost', 'RawBoostQueries');
             if (is_array($rawBoostQueries) && !empty($rawBoostQueries)) {
                 $boostQueryString .= ' ' . implode(' ', $rawBoostQueries);
             }
             $handlerParameters = array('q' => $searchText, 'bq' => $boostQueryString, 'qf' => implode(' ', array_merge($queryFields, $extraFieldsToSearch)), 'qt' => $queryHandler);
     }
     // Handle boost functions :
     $boostFunctionsParamList = $this->buildBoostFunctions($boostFunctions, $handlerParameters);
     // special handling of filters in the case of distributed search filters
     // incorporate distributed search filters if defined with an OR expression, and AND-ing all others
     // need to do this as multiple fq elements are otherwise AND-ed by the Solr backend
     // when using this to search across a dedicated set of languages, it will still be valid with the ezp permission
     // scheme
     if (!empty($shardFilterQuery)) {
         $fqString = '((' . implode(') AND (', $filterQuery) . ')) OR ((' . implode(') OR (', $shardFilterQuery) . '))';
         // modify the filterQuery array with this single string as the only element
         $filterQuery = array($fqString);
     }
     // Document transformer fields since eZ Find 5.4
     $docTransformerFields = array('[elevated]');
     $fieldsToReturnString = eZSolr::getMetaFieldName('guid') . ' ' . eZSolr::getMetaFieldName('installation_id') . ' ' . eZSolr::getMetaFieldName('main_url_alias') . ' ' . eZSolr::getMetaFieldName('installation_url') . ' ' . eZSolr::getMetaFieldName('id') . ' ' . eZSolr::getMetaFieldName('main_node_id') . ' ' . eZSolr::getMetaFieldName('language_code') . ' ' . eZSolr::getMetaFieldName('name') . ' score ' . eZSolr::getMetaFieldName('published') . ' ' . eZSolr::getMetaFieldName('path_string') . ' ' . eZSolr::getMetaFieldName('main_path_string') . ' ' . eZSolr::getMetaFieldName('is_invisible') . ' ' . implode(' ', $docTransformerFields) . ' ' . implode(' ', $extraFieldsToReturn);
     if (!$asObjects) {
         if (empty($fieldsToReturn)) {
             // @todo: needs to be refined with Solr supporting globbing in fl argument, otherwise requests will be to heavy for large fields as for example binary file content
             $fieldsToReturnString = 'score, *';
         } else {
             $fieldsToReturnString .= ' ' . implode(',', $fieldsToReturn);
         }
     }
     $searchResultClusterParamList = array('clustering' => 'true');
     $searchResultClusterParamList = $this->buildSearchResultClusterQuery($searchResultClusterParams);
     eZDebugSetting::writeDebug('extension-ezfind-query', $searchResultClusterParamList, 'Cluster params');
     $queryParams = array_merge($handlerParameters, array('start' => $offset, 'rows' => $limit, 'sort' => $sortParameter, 'indent' => 'on', 'version' => '2.2', 'fl' => $fieldsToReturnString, 'fq' => $filterQuery, 'hl' => $eZFindIni->variable('HighLighting', 'Enabled'), 'hl.fl' => implode(' ', $highLightFields), 'hl.snippets' => $eZFindIni->variable('HighLighting', 'SnippetsPerField'), 'hl.fragsize' => $eZFindIni->variable('HighLighting', 'FragmentSize'), 'hl.requireFieldMatch' => $eZFindIni->variable('HighLighting', 'RequireFieldMatch'), 'hl.simple.pre' => $eZFindIni->variable('HighLighting', 'SimplePre'), 'hl.simple.post' => $eZFindIni->variable('HighLighting', 'SimplePost'), 'wt' => 'php'), $facetQueryParamList, $spellCheckParamList, $boostFunctionsParamList, $elevateParamList, $searchResultClusterParamList);
     if (isset($extendedAttributeFilter['id']) && isset($extendedAttributeFilter['params'])) {
         //single filter
         $extendedAttributeFilter = array($extendedAttributeFilter);
     }
     foreach ($extendedAttributeFilter as $filterDefinition) {
         if (isset($filterDefinition['id'])) {
             $filter = eZFindExtendedAttributeFilterFactory::getInstance($filterDefinition['id']);
             if ($filter) {
                 $filterParams = isset($filterDefinition['params']) ? $filterDefinition['params'] : array();
                 $queryParams = $filter->filterQueryParams($queryParams, $filterParams);
             }
         }
     }
     return $queryParams;
 }
    /**
     * @see ezfSolrDocumentFieldBase::getData()
     */
    public function getData()
    {
        $contentClassAttribute = $this->ContentObjectAttribute->attribute( 'contentclass_attribute' );

        switch ( $contentClassAttribute->attribute( 'data_type_string' ) )
        {
            case 'ezobjectrelation' :
                $returnArray = array();

                $defaultFieldName = parent::generateAttributeFieldName( $contentClassAttribute,
                                                                        self::$subattributesDefinition[self::DEFAULT_SUBATTRIBUTE] );
                $returnArray[$defaultFieldName] = $this->getPlainTextRepresentation();
                $relatedObject = $this->ContentObjectAttribute->content();

                if ( $relatedObject && $relatedObject->attribute( 'status' ) == eZContentObject::STATUS_PUBLISHED )
                {
                    // 1st, add content fields of the related object.
                    $baseList = $this->getBaseList( $relatedObject->attribute( 'current' ) );

                    foreach ( $baseList as $field )
                    {
                        $tmpClassAttribute = $field->ContentObjectAttribute->attribute( 'contentclass_attribute' );
                        $fieldName = $field->ContentObjectAttribute->attribute( 'contentclass_attribute_identifier' );
                        $fieldName = parent::generateSubattributeFieldName( $contentClassAttribute,
                                                                            $fieldName,
                                                                            self::getClassAttributeType( $tmpClassAttribute ) );

                        $finalValue = '';
                        if ( $tmpClassAttribute->attribute( 'data_type_string' ) == 'ezobjectrelation' or
                             $tmpClassAttribute->attribute( 'data_type_string' ) == 'ezobjectrelationlist' )
                        {
                            // The subattribute is in turn an object relation. Stop recursion and get full text representation.
                            $finalValue = $field->getPlainTextRepresentation();
                        }
                        else
                        {
                            $values = array_values( $field->getData() );
                            foreach ( $values as $value )
                            {
                                if ( is_array( $value ) )
                                {
                                    $finalValue .= implode( ' ', $value );
                                }
                                else
                                {
                                    $finalValue .= ' ' . $value;
                                }
                            }
                        }

                        $returnArray[$fieldName] = trim( $finalValue, "\t\r\n " );
                    }

                    // 2ndly, add meta fields of the related object.
                    $metaAttributeValues = eZSolr::getMetaAttributesForObject( $relatedObject );
                    foreach ( $metaAttributeValues as $metaInfo )
                    {
                        $returnArray[ezfSolrDocumentFieldBase::generateSubmetaFieldName( $metaInfo['name'], $contentClassAttribute )] = ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] );
                    }

                    return $returnArray;
                }
                break;
            case 'ezobjectrelationlist' :
            {
                $returnArray = array();
                $content = $this->ContentObjectAttribute->content();

                foreach ( $content['relation_list'] as $relationItem )
                {
                    $subObjectID = $relationItem['contentobject_id'];
                    if ( !$subObjectID )
                        continue;
                    $subObject = eZContentObjectVersion::fetchVersion( $relationItem['contentobject_version'], $subObjectID );
                    if ( !$subObject || $relationItem['in_trash'] )
                        continue;

                    // 1st create aggregated metadata fields
                    $metaAttributeValues = eZSolr::getMetaAttributesForObject( $subObject->attribute( 'contentobject' ) );
                    foreach ( $metaAttributeValues as $metaInfo )
                    {
                        $submetaFieldName = ezfSolrDocumentFieldBase::generateSubmetaFieldName( $metaInfo['name'], $contentClassAttribute );
                        if ( isset( $returnArray[$submetaFieldName] ) )
                        {
                            $returnArray[$submetaFieldName] = array_merge( $returnArray[$submetaFieldName], array( ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) ) );
                        }
                        else
                        {
                            $returnArray[$submetaFieldName] = array( ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) );
                        }
                    }
                }

                $defaultFieldName = parent::generateAttributeFieldName( $contentClassAttribute,
                                                                        self::$subattributesDefinition[self::DEFAULT_SUBATTRIBUTE] );
                $returnArray[$defaultFieldName] = $this->getPlainTextRepresentation();
                return $returnArray;
            }
                break;
            default:
            {
            } break;
        }
    }
}
// Ultimo giorno (Default)
if (!isset($days)) {
    $days = 1;
}
// Tutte le tematiche in OR
$tag_filters = array('or');
foreach ($tematiche as $tag) {
    $tag_filters[] = 'attr_tematica_lk: "' . $tag . '"';
}
// Data inizio è di $days giorni indietro
$_startDate = new DateTime();
$_endDate = new DateTime();
$_startDate->modify("-" . $days . " day");
$startDate = ezfSolrDocumentFieldBase::preProcessValue($_startDate->format('U'), 'date');
$endDate = ezfSolrDocumentFieldBase::preProcessValue($_endDate->format('U'), 'date');
// Composizione del filtro
$filters = array('and', 'meta_published_dt:[' . $startDate . ' TO ' . $endDate . ']', $tag_filters);
$params = array('SortBy' => array('meta_published_dt' => 'desc'), 'Filter' => $filters, 'SearchContentClassID' => array($class_id), 'SearchSubTreeArray' => array(eZINI::instance('content.ini')->variable('NodeSettings', 'RootNode')));
// Esecuzione query Solr
$solrSearch = new eZSolr();
$result = $solrSearch->search('', $params);
// Estrazione del NodeID
$node_ids = array();
foreach ($result['SearchResult'] as $object) {
    $node_ids[] = $object->ContentObject->mainNodeID();
}
// Output in JSON
header('Content-Type: application/json');
echo json_encode($node_ids);
// echo json_encode( $result['SearchResult'] ); // DEBUG
Exemplo n.º 5
0
    /**
     * Adds object $contentObject to the search database.
     *
     * @param eZContentObject $contentObject Object to add to search engine
     * @param bool $commit Whether to commit after adding the object.
              If set, run optimize() as well every 1000nd time this function is run.
     * @return bool True if the operation succeed.
     */
    function addObject( $contentObject, $commit = true )
    {
        // Add all translations to the document list
        $docList = array();

        // Check if we need to index this object after all
        // Exclude if class identifier is in the exclude list for classes
        $excludeClasses = $this->FindINI->variable( 'IndexExclude', 'ClassIdentifierList' );
        if ( $excludeClasses && in_array( $contentObject->attribute( 'class_identifier' ), $excludeClasses ) )
        {
            return true;
        }
        // Get global object values
        $mainNode = $contentObject->attribute( 'main_node' );
        if ( !$mainNode )
        {
            eZDebug::writeError( 'Unable to fetch main node for object: ' . $contentObject->attribute( 'id' ), __METHOD__ );
            return false;
        }

        $mainNodePathArray = $mainNode->attribute( 'path_array' );
        $mainNodeID = $mainNode->attribute( 'node_id' );
        // initialize array of parent node path ids, needed for multivalued path field and subtree filters
        $nodePathArray = array();

        //included in $nodePathArray
        //$pathArray = $mainNode->attribute( 'path_array' );
        $currentVersion = $contentObject->currentVersion();

        // Get object meta attributes.
        $metaAttributeValues = self::getMetaAttributesForObject( $contentObject );

        // Get node attributes.
        $nodeAttributeValues = array();
        foreach ( $contentObject->attribute( 'assigned_nodes' ) as $contentNode )
        {
            $nodeID = $contentNode->attribute( 'node_id' );
            foreach ( eZSolr::nodeAttributes() as $attributeName => $fieldType )
            {
                $nodeAttributeValues[$nodeID][] = array( 'name' => $attributeName,
                                                'value' => $contentNode->attribute( $attributeName ),
                                                'fieldType' => $fieldType );
            }
            $nodePathArray[] = $contentNode->attribute( 'path_array' );

        }

        // Check anonymous user access.
        if ( $this->FindINI->variable( 'SiteSettings', 'IndexPubliclyAvailable' ) == 'enabled' )
        {
            $anonymousUserID = $this->SiteINI->variable( 'UserSettings', 'AnonymousUserID' );
            $currentUserID = eZUser::currentUserID();
            $user = eZUser::instance( $anonymousUserID );
            eZUser::setCurrentlyLoggedInUser( $user, $anonymousUserID );
            $anonymousAccess = $contentObject->attribute( 'can_read' );
            $user = eZUser::instance( $currentUserID );
            eZUser::setCurrentlyLoggedInUser( $user, $currentUserID );
            $anonymousAccess = $anonymousAccess ? 'true' : 'false';
        }
        else
        {
            $anonymousAccess = 'false';
        }

        // Load index time boost factors if any
        //$boostMetaFields = $this->FindINI->variable( "IndexBoost", "MetaField" );
        $boostClasses = $this->FindINI->variable( 'IndexBoost', 'Class' );
        $boostAttributes = $this->FindINI->variable( 'IndexBoost', 'Attribute' );
        $boostDatatypes = $this->FindINI->variable( 'IndexBoost', 'Datatype' );
        $reverseRelatedScale = $this->FindINI->variable( 'IndexBoost', 'ReverseRelatedScale' );

        // Initialise default doc boost
        $docBoost = 1.0;
        $contentClassIdentifier = $contentObject->attribute( 'class_identifier' );
        // Just test if the boost factor is defined by checking if it has a numeric value
        if ( isset( $boostClasses[$contentClassIdentifier] ) && is_numeric( $boostClasses[$contentClassIdentifier] ) )
        {
            $docBoost += $boostClasses[$contentClassIdentifier];
        }
        // Google like boosting, using eZ Publish reverseRelatedObjectCount
        $reverseRelatedObjectCount = $contentObject->reverseRelatedObjectCount();
        $docBoost += $reverseRelatedScale * $reverseRelatedObjectCount;

        //  Create the list of available languages for this version :
        $availableLanguages = $currentVersion->translationList( false, false );

        // Loop over each language version and create an eZSolrDoc for it
        foreach ( $availableLanguages as $languageCode )
        {
            $doc = new eZSolrDoc( $docBoost );
            // Set global unique object ID
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'guid' ), $this->guid( $contentObject, $languageCode ) );

            // Set installation identifier
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'installation_id' ), self::installationID() );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'installation_url' ),
                            $this->FindINI->variable( 'SiteSettings', 'URLProtocol' ) . $this->SiteINI->variable( 'SiteSettings', 'SiteURL' ) . '/' );

            // Set Object attributes
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'name' ), $contentObject->name( false, $languageCode ) );
            // Also add value to the "sort_name" field as "name" is unsortable, due to Solr limitation (tokenized field)
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'sort_name' ), $contentObject->name( false, $languageCode ) );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'anon_access' ), $anonymousAccess );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'language_code' ), $languageCode );
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'available_language_codes' ), $availableLanguages );

            if ( $owner = $contentObject->attribute( 'owner' ) )
            {
                // Set owner name
                $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'owner_name' ),
                                $owner->name( false, $languageCode ) );

                // Set owner group ID
                foreach ( $owner->attribute( 'parent_nodes' ) as $groupID )
                {
                    $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'owner_group_id' ), $groupID );
                }
            }

            // from eZ Publish 4.1 only: object states
            // so let's check if the content object has it
            if ( method_exists( $contentObject, 'stateIDArray' ) )
            {
                $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'object_states' ),
                                $contentObject->stateIDArray() );
            }

            // Set content object meta attribute values.
            foreach ( $metaAttributeValues as $metaInfo )
            {
                $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( $metaInfo['name'] ),
                                ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) );
            }

            // Set content node meta attribute values.
            foreach ( $nodeAttributeValues as $nodeID => $metaInfoArray )
            {
                foreach( $metaInfoArray as $metaInfo)
                {
                    $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( $metaInfo['name'] ),
                                ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) );
                }
            }

            // Main node gets single valued fields for sorting, using a dedicated prefix
            foreach ( $nodeAttributeValues[$mainNodeID] as $metaInfo )
            {
                $fieldName = 'main_node_' . ezfSolrDocumentFieldBase::generateMetaFieldName( $metaInfo['name'] );
                $doc->addField( $fieldName,
                                    ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'],
                                    $metaInfo['fieldType'] ) );
            }


            // Add main url_alias
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'main_url_alias' ), $mainNode->attribute( 'url_alias' ) );

            // Add main path_string
            $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'main_path_string' ), $mainNode->attribute( 'path_string' ) );

            // add nodeid of all parent nodes path elements
            foreach ( $nodePathArray as $pathArray )
            {
                foreach ( $pathArray as $pathNodeID)
                {
                    $doc->addField( ezfSolrDocumentFieldBase::generateMetaFieldName( 'path' ), $pathNodeID );
                }
            }

            // Since eZ Fnd 2.3
            // cannot call metafield field bame constructor as we are creating multiple fields
            foreach ( $mainNodePathArray as $key => $pathNodeID )
            {
                $doc->addField( 'meta_main_path_element_' . $key . '_si', $pathNodeID );

            }

            eZContentObject::recursionProtectionStart();

            // Loop through all eZContentObjectAttributes and add them to the Solr document.
            // @since eZ Find 2.3: look for the attribute storage setting

            $doAttributeStorage = ( ( $this->FindINI->variable( 'IndexOptions', 'EnableSolrAttributeStorage' ) ) === 'true' ) ? true : false;

            if ( $doAttributeStorage )
            {
                $allAttributeData = array();
            }

            foreach ( $currentVersion->contentObjectAttributes( $languageCode ) as $attribute )
            {
                $metaDataText = '';
                $classAttribute = $attribute->contentClassAttribute();
                $attributeIdentifier = $classAttribute->attribute( 'identifier' );
                $combinedIdentifier = $contentClassIdentifier . '/' . $attributeIdentifier;
                $boostAttribute = false;
                if ( isset( $boostAttributes[$attributeIdentifier]) && is_numeric( $boostAttributes[$attributeIdentifier]))
                {
                    $boostAttribute = $boostAttributes[$attributeIdentifier];
                }
                if ( isset( $boostAttributes[$combinedIdentifier]) && is_numeric( $boostAttributes[$combinedIdentifier]))
                {
                    $boostAttribute += $boostAttributes[$combinedIdentifier];
                }
                if ( $classAttribute->attribute( 'is_searchable' ) == 1 )
                {
                    $documentFieldBase = ezfSolrDocumentFieldBase::getInstance( $attribute );
                    $this->addFieldBaseToDoc( $documentFieldBase, $doc, $boostAttribute );
                }

                if ( $doAttributeStorage )
                {
                    $storageFieldName = ezfSolrStorage::getSolrStorageFieldName( $attributeIdentifier );
                    $attributeData = ezfSolrStorage::getAttributeData( $attribute );
                    $allAttributeData['data_map'][$attributeIdentifier] = $attributeData;
                    $doc->addField( $storageFieldName, ezfSolrStorage::serializeData( $attributeData ) );
                }
            }
            eZContentObject::recursionProtectionEnd();

            if ( $doAttributeStorage )
            {
                $doc->addField( 'as_all_bst', ezfSolrStorage::serializeData( $allAttributeData ) );
            }

            $docList[$languageCode] = $doc;
        }

        // Since eZFind 2.7: indexhooks
        $generalPlugins = $this->FindINI->variable( 'IndexPlugins', 'General' );
        $classPlugins   = $this->FindINI->variable( 'IndexPlugins', 'Class' );
        if ( !empty( $generalPlugins ) )
        {
            foreach ( $generalPlugins as $pluginClassString )
            {
                if( !class_exists( $pluginClassString ) )
                {
                    eZDebug::writeError( "Unable to find the PHP class '$classname' defined for index time plugins for eZ Find", __METHOD__ );
                    continue;
                }
                $plugin = new $pluginClassString;
                if ( $plugin instanceof ezfIndexPlugin )
                {
                    $plugin->modify( $contentObject, $docList );
                }
            }
        }

        if (array_key_exists($contentObject->attribute( 'class_identifier' ), $classPlugins ) )
        {
            $pluginClassString = $classPlugins[$contentObject->attribute( 'class_identifier' )];
            if ( class_exists( $pluginClassString ) )
            {
                $plugin = new $pluginClassString;
                if ($plugin instanceof ezfIndexPlugin)
                {
                        $plugin->modify( $contentObject, $docList );
                }
            }
        }

        $optimize = false;
        if ( $this->FindINI->variable( 'IndexOptions', 'DisableDirectCommits' ) === 'true' )
        {
            $commit = false;
        }
        $commitWithin = 0;
        if ( $this->FindINI->variable( 'IndexOptions', 'CommitWithin' ) > 0 )
        {
            $commitWithin = $this->FindINI->variable( 'IndexOptions', 'CommitWithin' );
        }
        if ( $commit && ( $this->FindINI->variable( 'IndexOptions', 'OptimizeOnCommit' ) === 'enabled' ) )
        {
            $optimize = true;
        }

        if ( $this->UseMultiLanguageCores === true)
        {
            $result = true;
            foreach ( $availableLanguages as $languageCode )
            {
                $languageResult = $this->SolrLanguageShards[$languageCode]->addDocs( array( $docList[$languageCode] ), $commit, $optimize, $commitWithin );
                if ( !$languageResult )
                {
                    $result = false;
                }
            }
            return $result;
        }
        else
        {
            return $this->Solr->addDocs( $docList, $commit, $optimize, $commitWithin );
        }


    }
 protected function getDateFilter()
 {
     $startDateTime = DateTime::createFromFormat('H i s n j Y', implode(' ', $this->startDateArray), self::timezone());
     $startTimeStamp = $startDateTime->format('U');
     $endDateTime = clone $startDateTime;
     $this->addInterval($endDateTime);
     $endTimeStamp = $endDateTime->format('U');
     $endDateTime = $endTimeStamp > $startTimeStamp ? $endTimeStamp-- : $startTimeStamp--;
     $startDate = ezfSolrDocumentFieldBase::preProcessValue($startTimeStamp, 'date');
     $endDate = ezfSolrDocumentFieldBase::preProcessValue($endTimeStamp, 'date');
     if ($endTimeStamp > $startTimeStamp) {
         return array('meta_published_dt:[' . $startDate . ' TO ' . $endDate . ']');
     } else {
         return array('meta_published_dt:[' . $endDate . ' TO ' . $startDate . ']');
     }
 }
 /**
  * @see ezfSolrDocumentFieldBase::getData()
  */
 public function getData()
 {
     /** @var eZContentClassAttribute $contentClassAttribute */
     $contentClassAttribute = $this->ContentObjectAttribute->attribute('contentclass_attribute');
     switch ($contentClassAttribute->attribute('data_type_string')) {
         case 'ezobjectrelation':
             $returnArray = array();
             /** @var eZContentObject $relatedObject */
             $relatedObject = $this->ContentObjectAttribute->content();
             if ($relatedObject) {
                 $returnArray = $this->getArrayRelatedObject($relatedObject, $contentClassAttribute);
                 eZContentObject::clearCache(array($relatedObject->attribute('id')));
             }
             return $returnArray;
             break;
         case 'ezobjectrelationlist':
             $returnArray = array();
             $returnArrayRelatedObject = array();
             $content = $this->ContentObjectAttribute->content();
             $relationCount = count($content['relation_list']);
             foreach ($content['relation_list'] as $relationItem) {
                 $subObjectID = $relationItem['contentobject_id'];
                 if (!$subObjectID) {
                     continue;
                 }
                 /** @var eZContentObjectVersion $subObject */
                 $subObject = eZContentObjectVersion::fetchVersion($relationItem['contentobject_version'], $subObjectID);
                 if (!$subObject instanceof eZContentObjectVersion) {
                     $subObjectWrapper = eZContentObject::fetch($subObjectID);
                     if ($subObjectWrapper instanceof eZContentObject) {
                         $subObject = $subObjectWrapper->currentVersion();
                     } else {
                         continue;
                     }
                 }
                 /** @var eZContentObject $subContentObject */
                 $subContentObject = $subObject->attribute('contentobject');
                 if (intval($subContentObject->attribute('main_node_id')) == 0) {
                     continue;
                 }
                 $metaAttributeValues = eZSolr::getMetaAttributesForObject($subContentObject);
                 foreach ($metaAttributeValues as $metaInfo) {
                     $submetaFieldName = ezfSolrDocumentFieldBase::generateSubmetaFieldName($metaInfo['name'], $contentClassAttribute);
                     if (isset($returnArray[$submetaFieldName])) {
                         $returnArray[$submetaFieldName] = array_merge($returnArray[$submetaFieldName], array(ezfSolrDocumentFieldBase::preProcessValue($metaInfo['value'], $metaInfo['fieldType'])));
                     } else {
                         $returnArray[$submetaFieldName] = array(ezfSolrDocumentFieldBase::preProcessValue($metaInfo['value'], $metaInfo['fieldType']));
                     }
                 }
                 $nodeAttributeValues = array();
                 $nodePathArray = array();
                 /** @var eZContentObjectTreeNode $contentNode */
                 foreach ($subContentObject->attribute('assigned_nodes') as $contentNode) {
                     foreach (eZSolr::nodeAttributes() as $attributeName => $fieldType) {
                         $nodeAttributeValues[] = array('name' => $attributeName, 'value' => $contentNode->attribute($attributeName), 'fieldType' => $fieldType);
                     }
                     $nodePathArray[] = $contentNode->attribute('path_array');
                 }
                 //@todo questo non va... occorre correggere schema.xml?
                 //foreach ( $nodeAttributeValues as $metaInfo )
                 //{
                 //    $submetaFieldName = ezfSolrDocumentFieldBase::generateSubmetaFieldName( $metaInfo['name'], $contentClassAttribute );
                 //    if ( isset( $returnArray[$submetaFieldName] ) )
                 //    {
                 //        $returnArray[$submetaFieldName] = array_merge( $returnArray[$submetaFieldName],
                 //                                                       array( ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) ) );
                 //    }
                 //    else
                 //    {
                 //        $returnArray[$submetaFieldName] = array( ezfSolrDocumentFieldBase::preProcessValue( $metaInfo['value'], $metaInfo['fieldType'] ) );
                 //    }
                 //}
                 foreach ($nodePathArray as $pathArray) {
                     $submetaFieldName = ezfSolrDocumentFieldBase::generateSubmetaFieldName('path', $contentClassAttribute);
                     foreach ($pathArray as $pathNodeID) {
                         if (isset($returnArray[$submetaFieldName])) {
                             $returnArray[$submetaFieldName] = array_merge($returnArray[$submetaFieldName], array($pathNodeID));
                         } else {
                             $returnArray[$submetaFieldName] = array($pathNodeID);
                         }
                     }
                 }
                 if ($relationCount < 200) {
                     $returnArrayRelatedObject = $this->getArrayRelatedObject($subContentObject, $contentClassAttribute, $returnArrayRelatedObject);
                 } else {
                     $objectName = $subContentObject->name(false, $this->ContentObjectAttribute->attribute('language_code'));
                     $fieldName = parent::generateSubattributeFieldName($contentClassAttribute, 'name', self::DEFAULT_SUBATTRIBUTE_TYPE);
                     if (isset($returnArrayRelatedObject[$fieldName])) {
                         $returnArrayRelatedObject[$fieldName][] = $objectName;
                     } else {
                         $returnArrayRelatedObject[$fieldName] = array($objectName);
                     }
                 }
                 $returnArray = array_merge_recursive($returnArray, $returnArrayRelatedObject);
                 eZContentObject::clearCache(array($subContentObject->attribute('id')));
             }
             $defaultFieldName = parent::generateAttributeFieldName($contentClassAttribute, self::$subattributesDefinition[self::DEFAULT_SUBATTRIBUTE]);
             $stringFieldName = parent::generateAttributeFieldName($contentClassAttribute, 'string');
             $returnArray[$defaultFieldName] = $this->getPlainTextRepresentation();
             $returnArray[$stringFieldName] = $this->getPlainTextRepresentation();
             $result = array();
             foreach ($returnArray as $key => $value) {
                 if (is_array($value)) {
                     $value = array_unique($value);
                 }
                 $result[$key] = $value;
             }
             return $result;
             break;
     }
     return array();
 }
 /**
  * test for getData()
  */
 public function testGetData()
 {
     $providerArray = array();
     #start 1 : the simplest attribute
     $content1 = "Hello world";
     $ezcca1 = new eZContentClassAttribute(array('identifier' => 'title', 'data_type_string' => 'ezstring'));
     $ezcoa1 = new eZContentObjectAttributeTester(array("data_type_string" => 'ezstring', "id" => 100123, "data_text" => $content1, "contentclass_attribute" => $ezcca1));
     $fieldName1 = ezfSolrDocumentFieldBase::getFieldName($ezcca1);
     $expectedData1 = array($fieldName1 => $content1);
     $providerArray[] = array($expectedData1, $ezcoa1);
     #end 1
     #start 2 : attribute with subattributes
     $ezcca2 = new eZContentClassAttribute(array('identifier' => 'dummy', 'data_type_string' => 'dummy_example'));
     $ezcoa2 = new eZContentObjectAttributeTester(array("data_type_string" => 'dummy_example', "id" => 100124, "contentclass_attribute" => $ezcca2));
     $fieldList2 = ezfSolrDocumentFieldBase::getFieldNameList($ezcca2);
     $expectedData2 = array();
     foreach ($fieldList2 as $fieldName) {
         $expectedData2[$fieldName] = 'DATA_FOR_' . $fieldName;
     }
     $fieldName2 = ezfSolrDocumentFieldBase::getFieldName($ezcca2);
     $providerArray[] = array($expectedData2, $ezcoa2);
     #end 2
     #start 3 : object relations
     $expectedData3 = array();
     $tester3 = new ezfSolrDocumentFieldObjectRelationTester(new eZContentObjectAttribute(array()));
     $time3 = time();
     $image3 = new ezpObject("image", 2);
     $image3->name = __METHOD__ . $time3;
     $image3->caption = __METHOD__ . $time3;
     $imageId3 = $image3->publish();
     // $image3->object->clearCache();
     $dataMapImage3 = $image3->dataMap;
     // eZContentObjectAttribute objects, attributes of the related Image
     $imageName3 = $dataMapImage3['name'];
     $imageCaption3 = $dataMapImage3['caption'];
     $article3 = new ezpObject("article", 2);
     $articleId3 = $article3->publish();
     // Create object relation
     $article3->object->addContentObjectRelation($imageId3, $article3->current_version, 154, eZContentObject::RELATION_ATTRIBUTE);
     $dataMapArticle3 = $article3->attribute('data_map');
     $ezcoa3 = $dataMapArticle3['image'];
     $ezcoa3->setAttribute('data_int', $imageId3);
     $ezcoa3->store();
     $ezcca3 = $ezcoa3->attribute('contentclass_attribute');
     $defaultFieldName3 = ezfSolrDocumentFieldBase::generateAttributeFieldName($ezcca3, ezfSolrDocumentFieldObjectRelation::$subattributesDefinition[ezfSolrDocumentFieldObjectRelation::DEFAULT_SUBATTRIBUTE]);
     $expectedData3[$defaultFieldName3] = $tester3->getPlainTextRepresentation($ezcoa3);
     // required to allow another call to metaData()
     // on $ezcoa3 in getPlainTextRepresentation, called from the getData() method :
     eZContentObject::recursionProtectionEnd();
     $fieldNameImageName3 = ezfSolrDocumentFieldBase::generateSubattributeFieldName($ezcca3, $imageName3->attribute('contentclass_attribute_identifier'), ezfSolrDocumentFieldObjectRelation::getClassAttributeType($imageName3->attribute('contentclass_attribute')));
     $expectedData3[$fieldNameImageName3] = trim(implode(' ', array_values(ezfSolrDocumentFieldBase::getInstance($imageName3)->getData())), "\t\r\n ");
     $fieldNameImageCaption3 = ezfSolrDocumentFieldBase::generateSubattributeFieldName($ezcca3, $imageCaption3->attribute('contentclass_attribute_identifier'), ezfSolrDocumentFieldObjectRelation::getClassAttributeType($imageCaption3->attribute('contentclass_attribute')));
     $expectedData3[$fieldNameImageCaption3] = trim(implode(' ', array_values(ezfSolrDocumentFieldBase::getInstance($imageCaption3)->getData())), "\t\r\n ");
     $image3 = eZContentObject::fetch($imageId3);
     $metaAttributeValues = eZSolr::getMetaAttributesForObject($image3);
     foreach ($metaAttributeValues as $metaInfo) {
         $expectedData3[ezfSolrDocumentFieldBase::generateSubmetaFieldName($metaInfo['name'], $ezcca3)] = ezfSolrDocumentFieldBase::preProcessValue($metaInfo['value'], $metaInfo['fieldType']);
     }
     $providerArray[] = array($expectedData3, $ezcoa3);
     #end 3
     // Let's perform the actual testing :
     foreach ($providerArray as $input) {
         $expected = $input[0];
         $contentObjectAttribute = $input[1];
         $instance = ezfSolrDocumentFieldBase::getInstance($contentObjectAttribute);
         self::assertEquals($expected, $instance->getData());
     }
 }
 public function fetch()
 {
     $startDateArray = array('hour' => '00', 'minute' => '00', 'second' => '00', 'month' => $this->parameters['month'], 'day' => $this->parameters['day'], 'year' => $this->parameters['year']);
     $originalStartDateTime = DateTime::createFromFormat('H i s n j Y', implode(' ', $startDateArray), self::timezone());
     $this->parameters['picker_date'] = date(self::PICKER_DATE_FORMAT, $originalStartDateTime->getTimestamp());
     if ($this->parameters['interval'] == self::INTERVAL_MONTH) {
         $startDateArray['day'] = 1;
     }
     $startDateTime = DateTime::createFromFormat('H i s n j Y', implode(' ', $startDateArray), self::timezone());
     if (!$startDateTime instanceof DateTime) {
         throw new Exception("Data non valida");
     }
     $interval = new DateInterval($this->parameters['interval']);
     if (!$interval instanceof DateInterval) {
         throw new Exception("Intervallo non valido");
     }
     // start day
     $this->parameters['timestamp'] = $startDateTime->getTimestamp();
     $this->parameters['days_of_month'] = date('t', $startDateTime->getTimestamp());
     $this->parameters['start_weekday'] = date('w', $startDateTime->getTimestamp());
     $endOfMonthArray = array_merge($startDateArray, array('day' => $this->parameters['days_of_month']));
     $endOfMonthDateTime = DateTime::createFromFormat('H i s n j Y', implode(' ', $endOfMonthArray), self::timezone());
     $this->parameters['end_weekday'] = date('w', $endOfMonthDateTime->getTimestamp());
     $fromTimeStamp = $startDateTime->format('U');
     $this->parameters['search_from_solr'] = ezfSolrDocumentFieldBase::preProcessValue($startDateTime->getTimestamp(), 'date');
     $this->parameters['search_from_timestamp'] = $startDateTime->getTimestamp();
     // end day
     $endDateTime = clone $startDateTime;
     $endDateTime->add($interval);
     $endTimeStamp = $endDateTime->format('U');
     $this->parameters['search_to_solr'] = ezfSolrDocumentFieldBase::preProcessValue($endDateTime->getTimestamp() - 1, 'date');
     $this->parameters['search_to_timestamp'] = $endDateTime->getTimestamp();
     $this->parameters['search_to_picker_date'] = date(self::PICKER_DATE_FORMAT, $endDateTime->getTimestamp());
     // filter
     $this->filters[] = array('or', 'attr_from_time_dt:[' . $this->parameters['search_from_solr'] . ' TO ' . $this->parameters['search_to_solr'] . ']', 'attr_to_time_dt:[' . $this->parameters['search_from_solr'] . ' TO ' . $this->parameters['search_to_solr'] . ']', array('and', 'attr_from_time_dt:[* TO ' . $this->parameters['search_from_solr'] . ']', 'attr_to_time_dt:[' . $this->parameters['search_to_solr'] . ' TO *]'));
     $facets = array();
     //esempio: $this->parameters['Materia'] = '"Economia e diritto"';
     foreach (self::relatedParameters() as $fieldIdentifier => $fieldName) {
         if (isset($this->parameters[$fieldName]) && $this->parameters[$fieldName] !== false) {
             if (is_array($this->parameters[$fieldName])) {
                 $orFilter = array('or');
                 foreach ($this->parameters[$fieldName] as $value) {
                     $filterValue = addcslashes($value, '"');
                     $orFilter[] = "subattr_{$fieldIdentifier}___name____s:\"{$filterValue}\"";
                 }
                 $this->filters[] = $orFilter;
             } else {
                 $filterValue = addcslashes($this->parameters[$fieldName], '"');
                 $this->filters[] = "subattr_{$fieldIdentifier}___name____s:\"{$filterValue}\"";
             }
         }
         $facets[] = array('field' => "subattr_{$fieldIdentifier}___name____s", 'name' => $fieldName, 'limit' => 100, 'sort' => 'alpha');
     }
     if (is_array($this->parameters['filter'])) {
         $this->filters = array_merge($this->filters, $this->parameters['filter']);
     }
     $sortBy = array('attr_priority_si' => 'desc', 'attr_special_b' => 'desc');
     if (class_exists('ezfIndexEventDuration')) {
         $sortBy['extra_event_duration_s'] = 'asc';
     }
     $sortBy['attr_from_time_dt'] = 'asc';
     $solrFetchParams = array('SearchOffset' => 0, 'SearchLimit' => 1000, 'Facet' => $facets, 'SortBy' => $sortBy, 'Filter' => $this->filters, 'SearchContentClassID' => null, 'SearchSectionID' => null, 'SearchSubTreeArray' => $this->parameters['subtree'], 'AsObjects' => false, 'SpellCheck' => null, 'IgnoreVisibility' => null, 'Limitation' => null, 'BoostFunctions' => null, 'QueryHandler' => 'ezpublish', 'EnableElevation' => true, 'ForceElevation' => true, 'SearchDate' => null, 'DistributedSearch' => null, 'FieldsToReturn' => self::fieldsToReturn(), 'SearchResultClustering' => null, 'ExtendedAttributeFilter' => array());
     $solrSearch = new OCSolr();
     $solrResult = $solrSearch->search($this->parameters['query'], $solrFetchParams);
     //eZDebug::writeNotice( $this->filters, __METHOD__ );
     //eZDebug::writeNotice( $solrResult, __METHOD__ );
     $this->data['parameters'] = $this->parameters;
     $this->data['fetch_parameters'] = $solrFetchParams;
     $facetFields = $solrResult['SearchExtras']->attribute('facet_fields');
     //eZDebug::writeNotice( $solrResult['SearchExtras'], __METHOD__ );
     $resultFacets = array();
     foreach ($facets as $index => $facet) {
         if (isset($facetFields[$index]['queryLimit']) && !empty($facetFields[$index]['queryLimit'])) {
             if (isset($facetFields[$index]['fieldList'])) {
                 foreach ($facetFields[$index]['fieldList'] as $key => $value) {
                     $resultFacets[$facet['name']][] = $key;
                 }
             } else {
                 foreach ($facetFields[$index]['nameList'] as $key => $value) {
                     $resultFacets[$facet['name']][] = $key;
                 }
             }
         }
     }
     $this->data['search_facets'] = $this->sortFacets($resultFacets);
     $events = array();
     foreach ($solrResult['SearchResult'] as $item) {
         $event = OCCalendarItem::fromEzfindResultArray($item);
         if ($event->isValid()) {
             $events[] = $event;
         }
     }
     $timeTableEvents = $this->fetchTimeTableEvents();
     if (count($timeTableEvents)) {
         $events = self::reorderEvents(array_merge($events, $timeTableEvents));
     }
     //eZDebug::writeNotice( $events, __METHOD__ );
     $this->data['search_count'] = count($events);
     $eventsByDay = array();
     $byDayInterval = new DateInterval('P1D');
     $byDayPeriod = new DatePeriod($startDateTime, $byDayInterval, $endDateTime);
     foreach ($byDayPeriod as $date) {
         $identifier = $date->format(self::FULLDAY_IDENTIFIER_FORMAT);
         $calendarDay = new OCCalendarDay($identifier);
         $calendarDay->addEvents($events);
         $eventsByDay[$identifier] = $calendarDay;
     }
     $this->data['events'] = $events;
     $this->data['day_by_day'] = $eventsByDay;
     //eZDebug::writeNotice( $eventsByDay, __METHOD__ );
     //eZDebug::writeNotice( $this->data['search_facets'], __METHOD__ );
 }