Get the select object to use for RawTokenAnswerRows

@param array $filter
@param type $surveyId
@param type $sourceSurveyId
@return \Zend_Db_Select
171009
public function getRawTokenAnswerRowsSelect(array $filter, $surveyId, $sourceSurveyId = null) {
        if (null === $sourceSurveyId) {
            $sourceSurveyId = $this->_getSid($surveyId);
        }

        $lsDb = $this->getSourceDatabase();
        $lsSurveyTable = $this->_getSurveyTableName($sourceSurveyId);
        $lsTokenTable  = $this->_getTokenTableName($sourceSurveyId);
        $tokenField    = $lsSurveyTable . '.token';

        $quotedTokenTable  = $lsDb->quoteIdentifier($lsTokenTable . '.token');
        $quotedSurveyTable = $lsDb->quoteIdentifier($lsSurveyTable . '.token');

        $select = $lsDb->select();
        $select->from($lsTokenTable, $this->_attributeMap)
               ->join($lsSurveyTable, $quotedTokenTable . ' = ' . $quotedSurveyTable);

        //Now process the filters
        if (is_array($filter)) {
            //first preprocess the tokens
            if (isset($filter['token'])) {
                foreach ((array) $filter['token'] as $key => $tokenId) {
                    $token = $this->_getToken($tokenId);

                    $filter[$tokenField][$key] = $token;
                }
                unset($filter['token']);
            }

            // now map the attributes to the right fields
            foreach ($this->_attributeMap as $name => $field) {
                if (isset($filter[$name])) {
                    $filter[$field] = $filter[$name];
                    unset($filter[$name]);
                }
            }
        }

        // Add limit / offset to select and remove from filter
        $this->filterLimitOffset($filter, $select);

        foreach ($filter as $field => $values) {
            $field = $lsDb->quoteIdentifier($field);
            if (is_array($values)) {
                $select->where("$field IN (?)", array_values($values));
            } else {
                $select->where("$field = ?", $values);
            }
        }

        if (\Gems_Tracker::$verbose) {
            \MUtil_Echo::r($select->__toString(), 'Select');
        }

        return $select;
    }
1205680
public function execute($sourceId = null, $sourceSurveyId = null, $surveyId = null)
    {
        $batch = $this->getBatch();

        if ($surveyId) {
            $survey = $this->loader->getTracker()->getSurvey($surveyId);
        } else {
            $survey = $this->loader->getTracker()->getSurveyBySourceId($sourceSurveyId, $sourceId);
        }

        if (! $survey->isActive()) {
            return;
        }

        // Now save the questions
        $answerModel = $survey->getAnswerModel('en');
        
        $hash = $survey->calculateHash();
        
        if ($survey->getHash() === $hash) {
            return;
        }
        
        $survey->setHash($hash, $this->loader->getCurrentUser()->getUserId());

        foreach ($answerModel->getItemsOrdered() as $order => $name) {
            if (true === $answerModel->get($name, 'survey_question')) {
                $batch->addTask('Tracker_RefreshQuestion', $surveyId, $name, $order);
            }
        }

        // If we have a response database, create a view on the answers
        if ($this->project->hasResponseDatabase()) {
            $this->replaceCreateView($survey, $answerModel);
        }
    }
1120896
public function buildFilterRulesForUsedOnly($filter, $idList = [])
    {
        $result = $this
            ->getConnection()
            ->createQueryBuilder()
            ->select('value_id AS id')
            ->from('tl_metamodel_tag_relation')
            ->where('att_id=:attId')
            ->groupBy('value_id')
            ->setParameter('attId', $this->get('id'));

        if (!empty($idList)) {
            $result
                ->andWhere('item_id IN (:itemIds)')
                ->setParameter('itemIds', $idList, Connection::PARAM_STR_ARRAY);
        }

        $filter->addFilterRule(SimpleQuery::createFromQueryBuilder($result));
    }
341298
public function &getCustomRoleRefs( $filter = array(), $sort = true )
	{
		// Make sure the filter is initialized and contains lowercase values
		if ( ! is_array( $filter ) ) $filter = array();
		$filter = array_flip( array_map( 'strtolower', $filter ) );

		$refs = $this->customRoles;

		/**
		 * @var array $result
		 */
		$result = array();

		foreach ( $refs as $refKey => $ref )
		{
			// Apply the filter if one is provided
			if ( count( $filter ) && ! isset( $filter[ strtolower( $refKey ) ] ) ) continue;

			$result[ $refKey ] = $this->customRoles[ $refKey ];

			$linkElement = null;

			// Look for the corresponding link element
			foreach ( $this->roleTypes as $link => $role )
			{
				if ( ! isset( $role[ $refKey ] ) )
				{
					continue;
				}

				$linkElement = $link;
				break;
			}

			if ( is_null( $linkElement ) )
			{
				continue;
			}

			$description = $this->getCustomLinkRoleDescription( $ref, $linkElement, "Custom link role" );
			$result[ $refKey ]['text'] = $description ? $description : "";

			// Remove any prohibited arcs
			if ( isset( $result[ $refKey ]['arcs'] ) && count( $result[ $refKey ]['arcs'] ) )
			{
				$arcs =& $result[ $refKey ]['arcs'];
				foreach ( $arcs as $from => $targets )
				{
					foreach ( $targets as $to => $node )
					{
						if ( $node['use'] == XBRL_Constants::$xlinkUseOptional ) continue;
						unset( $arcs[ $from ][ $to ] );
					}

					if ( count( $arcs[ $from ] ) ) continue;
					unset( $arcs[ $from ] );
				}
			}
		}

		if ( $sort )
		{
			$this->sortRoleRefs( $result );
		}

		return $result;
	}
296822
public TypedQuery<T> select(Filter filter, OrderBy orderBy) {
        CriteriaQuery<T> query = cb.createQuery(getEntityClass());
        Root<T> from = query.from(getEntityClass());

        CriteriaMapper criteriaMapper = new CriteriaMapper(from, cb);

        if (orderBy != null) {
            query.orderBy(criteriaMapper.create(orderBy));
        }
        if (filter != null) {
            query.where(criteriaMapper.create(filter));
        }

        return getEntityManager().createQuery(query);
    }
955988
public function fetchAll($source, $filter = [], $options = [], $secondaryPreferred = true)
    {
        $namespace = strpos($source, '.') !== false ? $source : ($this->_default_db . '.' . $source);

        $this->eventsManager->fireEvent('mongodb:beforeQuery', $this, compact('namespace', 'filter', 'options'));

        /** @var \ManaPHP\Mongodb\ConnectionInterface $connection */
        $connection = $this->poolManager->pop($this);
        try {
            $start_time = microtime(true);
            $result = $connection->fetchAll($namespace, $filter, $options, $secondaryPreferred);
            $elapsed = round(microtime(true) - $start_time, 3);
        } finally {
            $this->poolManager->push($this, $connection);
        }

        $this->eventsManager->fireEvent('mongodb:afterQuery', $this, compact('namespace', 'filter', 'options', 'result', 'elapsed'));

        $this->logger->debug(compact('namespace', 'filter', 'options', 'result', 'elapsed'), 'mongodb.query');
        return $result;
    }
602676
protected function getQueryCondition(
        Criterion $filter,
        SelectQuery $query,
        array $languageFilter
    ) {
        $condition = $query->expr->lAnd(
            $this->criteriaConverter->convertCriteria($query, $filter, $languageFilter),
            $query->expr->eq(
                'ezcontentobject.status',
                ContentInfo::STATUS_PUBLISHED
            ),
            $query->expr->eq(
                'ezcontentobject_version.status',
                VersionInfo::STATUS_PUBLISHED
            )
        );

        // If not main-languages query
        if (!empty($languageFilter['languages'])) {
            $condition = $query->expr->lAnd(
                $condition,
                $query->expr->gt(
                    $query->expr->bitAnd(
                        $this->handler->quoteColumn('language_mask', 'ezcontentobject'),
                        $query->bindValue(
                            $this->getLanguageMask($languageFilter),
                            null,
                            PDO::PARAM_INT
                        )
                    ),
                    $query->bindValue(0, null, PDO::PARAM_INT)
                )
            );
        }

        return $condition;
    }
413827
private function getParamsFromFilter(FilterBuilder $filter)
    {
        $result  = [];
        $must    = [];
        $mustNot = [];

        $params = $filter->getParams();

        if ($params['entities']) {
            $result['index'] = $params['entities'];
        }

        if (isset($params['keyword'])) {
            $must[] = new MultiMatchQuery($params['keyword']['value'], $params['keyword']['fields']);
        }

        foreach ($params['params'] ?? [] as $param) {
            list($query, $operator) = $param->createFilter();

            if ($operator == FilterOperators::IN) {
                $must[] = $query;
            } else {
                $mustNot[] = $query;
            }

        }

        if ($mustNot || $must) {

            $query = new QueryBuilder();
            if ($mustNot) {
                $query->setMustNot(new MustNotQuery($mustNot));
            }
            if ($must) {
                $query->setMust(new MustQuery($must));
            }

            $result['query'] = $query->toArray();
        }

        return $result;
    }
1051985
public function getSearchRequest($filter, $limit = 1, $conditions = [])
    {
        $self = $this;
        $knownFilters = $this->_getSearchFilters();
        $request = new StorageDataRequest(
            [$filter, $limit, $conditions],
            function ($filter, $limit, $conditions) use ($self, $knownFilters) {
                $items = $self->getAllItems();
                $results = [];
                $filterRules = [];
                
                foreach ($filter as $filterRequest) {
                    if (\count($filterRequest) === 3) {
                        list ($key, $compare, $compareValue) = $filterRequest;
                        
                        if (isset($knownFilters[$compare])) {
                            $filterRules[] = [$key, $knownFilters[$compare], $compareValue];
                        } else {
                            trigger_error('Comparator not found for filter: '.json_encode($filterRequest).'');
                        }
                    } else {
                        trigger_error('Strange filter: less than 3 parameters, '.json_encode($filterRequest));
                    }
                }
                
                foreach ($items as $id) {
                    $pointer = $self->getPointer($id);
                    $isOk = true;
                    if ($pointer) {
                        $record = json_decode(stream_get_contents($pointer), true);
                        
                        if (isset($record[self::F_DATA])) {
                            foreach ($filterRules as $filterRule) {
                                list ($key, $function, $filterRequest) = $filterRule;
        
                                $isOk = $isOk && call_user_func($function, $record[self::F_DATA][$key] ?? null, $filterRequest);
        
                                if (!$isOk) {
                                    break;
                                }
                            }
    
                            if ($isOk) {
                                $results[$id] = [$this->primaryKey => $id] + $record[self::F_DATA];
                            }    
                        }
                        
                        $self->closePointer($pointer);
                        
                        if (count($results) >= $limit) {
                            break;
                        }
                    }
                }
                
                if ($results && $conditions) {
                    $self->applyConditions($results, $conditions);
                }
            
                return $results;
            }
        );
    
        return $request;
    }
1306073
public function select($query, $bindings = [], $useReadPdo = true)
    {
        $query .= ' ALLOW FILTERING';

        return $this->statement($query, $bindings);
    }
333220
public function findByFilter(Filter $filter, $limit = null, $offset = 0, $order = null)
    {
        return $this->findByCriteria($filter->getCriteria(), $limit, $offset, $order);
    }
750787
public function getCompletedTokens($tokenIds, $sourceSurveyId)
    {
        $lsDb       = $this->getSourceDatabase();
        $lsToken   = $this->_getTokenTableName($sourceSurveyId);

        // Make sure we use tokens in the format LimeSurvey likes
        $tokens = array_map(array($this, '_getToken'), $tokenIds);

        $sql = $lsDb->select()
                ->from($lsToken, array('token'))
                ->where('token IN (?)', $tokens)
                ->where('completed != ?', 'N');

        $completedTokens = $lsDb->fetchCol($sql);

        // Now make sure we return tokens GemsTracker likes
        if ($completedTokens) {
            $translatedTokens = array();

            // Can not use the map function here since we need a second parameter
            foreach($completedTokens as $token) {
                $translatedTokens[] = $this->_getToken($token, true);
            }

            return $translatedTokens;
        }

        return $completedTokens;
    }
753024
public function listResources($filter)
    {
        $alias = 'resource';
        $collection = $this->getThisCollection();

        $queryBuilder = $this->getRepository()
            ->createQueryBuilder($alias);

        // Build the filter on resources
        $this->filterQueryBuilder($queryBuilder, $filter, $collection, $alias);

        // Count the total number of resources
        $countQueryBuilder = clone $queryBuilder;
        $collectionIdentifier = $collection->getIdentifier();
        $totalNumberOfRows = $countQueryBuilder
            ->select($countQueryBuilder->expr()->count($alias . '.' . $collectionIdentifier))
            ->getQuery()
            ->getSingleScalarResult();

        // Paginate resources
        $this->paginateQueryBuilder($queryBuilder, $filter);

        // Finally, select all fields
        $queryBuilder->select($alias);

        $returnedResources = $this->loadResourcesFromQueryBuilder($queryBuilder, $this->getThisCollection());

        return Resource::formatResourcesJsonApi($returnedResources, $totalNumberOfRows);
    }
1000960
function select($fields=NULL,$filter=NULL,array $options=NULL,$ttl=0) {
		if (!$options)
			$options=[];
		$options+=[
			'group'=>NULL,
			'order'=>NULL,
			'limit'=>0,
			'offset'=>0
		];
		$tag='';
		if (is_array($ttl))
			list($ttl,$tag)=$ttl;
		$fw=\Base::instance();
		$cache=\Cache::instance();
		if (!($cached=$cache->exists($hash=$fw->hash($this->db->dsn().
			$fw->stringify([$fields,$filter,$options])).($tag?'.'.$tag:'').'.mongo',
			$result)) || !$ttl || $cached[0]+$ttl<microtime(TRUE)) {
			if ($options['group']) {
				$grp=$this->collection->group(
					$options['group']['keys'],
					$options['group']['initial'],
					$options['group']['reduce'],
					[
						'condition'=>$filter,
						'finalize'=>$options['group']['finalize']
					]
				);
				$tmp=$this->db->selectcollection(
					$fw->HOST.'.'.$fw->BASE.'.'.
					uniqid(NULL,TRUE).'.tmp'
				);
				$tmp->batchinsert($grp['retval'],['w'=>1]);
				$filter=[];
				$collection=$tmp;
			}
			else {
				$filter=$filter?:[];
				$collection=$this->collection;
			}
			if ($this->legacy) {
				$this->cursor=$collection->find($filter,$fields?:[]);
				if ($options['order'])
					$this->cursor=$this->cursor->sort($options['order']);
				if ($options['limit'])
					$this->cursor=$this->cursor->limit($options['limit']);
				if ($options['offset'])
					$this->cursor=$this->cursor->skip($options['offset']);
				$result=[];
				while ($this->cursor->hasnext())
					$result[]=$this->cursor->getnext();
			}
			else {
				$this->cursor=$collection->find($filter,[
					'sort'=>$options['order'],
					'limit'=>$options['limit'],
					'skip'=>$options['offset']
				]);
				$result=$this->cursor->toarray();
			}
			if ($options['group'])
				$tmp->drop();
			if ($fw->CACHE && $ttl)
				// Save to cache backend
				$cache->set($hash,$result,$ttl);
		}
		$out=[];
		foreach ($result as $doc)
			$out[]=$this->factory($doc);
		return $out;
	}
1100325
public function find(array $filter = [], array $options = [])
    {
        $options += ['typeMap' => $this->typeMap];
        $options = QueryOptionsResolver::resolveStatic($options);
        $typeMap = $options['typeMap'];
        unset($options['typeMap']);

        if (isset($options['readPreference'])) {
            $readPreference = $options['readPreference'];
            unset($options['readPreference']);
        } else {
            $readPreference = $this->readPreference;
        }

        $query = new Query($filter, $options);
        $query->setDefaultReadConcern($this->readConcern);

        $cursor = $this->manager->executeQuery(
            $this->getNamespace(),
            $query,
            $readPreference
        );

        $cursor->setTypeMap($typeMap);

        return $cursor;
    }
806489
public function getTokenInfo(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId, array $fields = null)
    {
        if (! $token->cacheHas(self::CACHE_TOKEN_INFO)) {
            if (null === $sourceSurveyId) {
                $sourceSurveyId = $this->_getSid($surveyId);
            }

            $lsTokens = $this->_getTokenTableName($sourceSurveyId);
            $tokenId  = $this->_getToken($token->getTokenId());

            $sql = 'SELECT *
                FROM ' . $lsTokens . '
                WHERE token = ? LIMIT 1';

            try {
                $result = $this->getSourceDatabase()->fetchRow($sql, $tokenId);
            } catch (\Zend_Db_Statement_Exception $exception) {
                $this->logger->logError($exception, $this->request);
                $result = false;
            }

            $token->cacheSet(self::CACHE_TOKEN_INFO, $result);
        } else {
            $result = $token->cacheGet(self::CACHE_TOKEN_INFO);
        }

        if ($fields !== null) $result = array_intersect_key((array) $result, array_flip($fields));

        return $result;
    }
1273478
public function getChannels($filter = null)
	{
		$channels = array();

		// Create the request
		$request = new client\Request('/api/channel/grid');
		
		if ($filter)
			$request->setFilter($filter);
		
		// Get the response
		$response = $this->_client->getResponse($request);
		$rawContent = $response->getContent();

		$content = json_decode($rawContent);

		foreach ($content->entries as $entry)
			$channels[] = model\Channel::fromRawEntry($entry);

		return $channels;
	}