@param string $search
@param string $language
@param array  $groupFilter

@return array
351794
protected function generateFilterSearch($search, $language, $groupFilter = array())
    {
        $groupFilter['labels.' . $language] =  new \MongoRegex('/.*'.$search.'.*/i');

        return array('$or' =>array(
            array('username' => new \MongoRegex('/.*'.$search.'.*/i')),
            $this->getReferenceFilter('groups', $groupFilter)
        ));
    }
199714
public List<Group> getGroups(String search) throws GitLabApiException {
        return (getGroups(search, getDefaultPerPage()).all());
    }
448941
public function find($searchTerm, $language, $season=1, $episode=null)
    {
        $showId = $this->getShowId($searchTerm);

        if (!$showId) {
            return array();
        }

        $showData = $this->getShowData($showId, $season);

        $results = array();

        $language = strtolower($language);

        $id = 1;

        foreach ($showData as $show) {
            if ($show->episode != $episode) {
                continue;
            }
            if ($language != 'all' && strtolower($show->language) != $language) {
                continue;
            }

            $show->id = $id;

            $results[$id] = $show;

            $id++;
        }

        return $results;
    }
942266
protected function filteredFind($filter = NULL, array $options = NULL, $ttl = 0, $count=false) {
		if ($this->grp_stack) {
			if ($this->dbsType == 'mongo') {
				$group = array(
					'keys' => $this->grp_stack['keys'],
					'reduce' => 'function (obj, prev) {'.$this->grp_stack['reduce'].'}',
					'initial' => $this->grp_stack['initial'],
					'finalize' => $this->grp_stack['finalize'],
				);
				if ($options && isset($options['group'])) {
					if(is_array($options['group']))
						$options['group'] = array_merge($options['group'],$group);
					else {
						$keys = explode(',',$options['group']);
						$keys = array_combine($keys,array_fill(0,count($keys),1));
						$group['keys'] = array_merge($group['keys'],$keys);
						$options['group'] = $group;
					}
				} else
					$options = array('group'=>$group);
			}
			if($this->dbsType == 'sql') {
				if ($options && isset($options['group']))
					$options['group'].= ','.$this->grp_stack;
				else
					$options['group'] = $this->grp_stack;
			}
			// Jig can't group yet, but pending enhancement https://github.com/bcosca/fatfree/pull/616
		}
		if ($this->dbsType == 'sql' && !$count) {
			$m_refl=new \ReflectionObject($this->mapper);
			$m_ad_prop=$m_refl->getProperty('adhoc');
			$m_ad_prop->setAccessible(true);
			$m_refl_adhoc=$m_ad_prop->getValue($this->mapper);
			$m_ad_prop->setAccessible(false);
			unset($m_ad_prop,$m_refl);
		}
		$hasJoin = array();
		if ($this->hasCond) {
			foreach($this->hasCond as $key => $hasCond) {
				$addToFilter = null;
				if ($deep = is_int(strpos($key,'.'))) {
					$key = rtrim($key,'.');
					$hasCond = array(null,null);
				}
				list($has_filter,$has_options) = $hasCond;
				$type = $this->fieldConf[$key]['relType'];
				$fromConf = $this->fieldConf[$key][$type];
				switch($type) {
					case 'has-one':
					case 'has-many':
						if (!is_array($fromConf))
							trigger_error(sprintf(self::E_REL_CONF_INC, $key),E_USER_ERROR);
						$id = $this->dbsType == 'sql' ? $this->primary : '_id';
						if ($type=='has-many' && isset($fromConf['relField'])
							&& $fromConf['hasRel'] == 'belongs-to-one')
							$id=$fromConf['relField'];
						// many-to-many
						if ($type == 'has-many' && $fromConf['hasRel'] == 'has-many') {
							if (!$deep && $this->dbsType == 'sql'
								&& !isset($has_options['limit']) && !isset($has_options['offset'])) {
								$hasJoin = array_merge($hasJoin,
									$this->_hasJoinMM_sql($key,$hasCond,$filter,$options));
								if (!isset($options['group']))
									$options['group'] = '';
								$groupFields = explode(',', preg_replace('/"/','',$options['group']));
								if (!in_array($this->table.'.'.$this->primary,$groupFields)) {
									$options['group'] = ($options['group']?',':'').$this->table.'.'.$this->primary;
									$groupFields[]=$this->table.'.'.$this->primary;
								}
								// all non-aggregated fields need to be present in the GROUP BY clause
								if (isset($m_refl_adhoc) && preg_match('/sybase|dblib|odbc|sqlsrv/i',$this->db->driver()))
									foreach (array_diff($this->mapper->fields(),array_keys($m_refl_adhoc)) as $field)
										if (!in_array($this->table.'.'.$field,$groupFields))
											$options['group'] .= ', '.$this->table.'.'.$field;
							}
							elseif ($result = $this->_hasRefsInMM($key,$has_filter,$has_options,$ttl))
								$addToFilter = array($id.' IN ?', $result);
						}
						// *-to-one
						elseif (!$deep && $this->dbsType == 'sql') {
							// use sub-query inclusion
							$has_filter=$this->mergeFilter([$has_filter,
								[$this->rel($key)->getTable().'.'.$fromConf[1].'='.$this->getTable().'.'.$id]]);
							$result = $this->_refSubQuery($key,$has_filter,$has_options);
							$addToFilter = ['exists('.$result[0].')']+$result[1];
						}
						elseif ($result = $this->_hasRefsIn($key,$has_filter,$has_options,$ttl))
							$addToFilter = array($id.' IN ?', $result);
						break;
					// one-to-*
					case 'belongs-to-one':
						if (!$deep && $this->dbsType == 'sql'
							&& !isset($has_options['limit']) && !isset($has_options['offset'])) {
							if (!is_array($fromConf))
								$fromConf = array($fromConf, '_id');
							$rel = $fromConf[0]::resolveConfiguration();
							if ($this->dbsType == 'sql' && $fromConf[1] == '_id')
								$fromConf[1] = $rel['primary'];
							$hasJoin[] = $this->_hasJoin_sql($key,$rel['table'],$hasCond,$filter,$options);
						} elseif ($result = $this->_hasRefsIn($key,$has_filter,$has_options,$ttl))
								$addToFilter = array($key.' IN ?', $result);
						break;
					default:
						trigger_error(self::E_HAS_COND,E_USER_ERROR);
				}
				if (isset($result) && !isset($addToFilter))
					return false;
				elseif (isset($addToFilter)) {
					if (!$filter)
						$filter = array('');
					if (!empty($filter[0]))
						$filter[0] .= ' and ';
					$cond = array_shift($addToFilter);
					if ($this->dbsType=='sql')
						$cond = $this->queryParser->sql_prependTableToFields($cond,$this->table);
					$filter[0] .= '('.$cond.')';
					$filter = array_merge($filter, $addToFilter);
				}
			}
			$this->hasCond = null;
		}
		$filter = $this->queryParser->prepareFilter($filter, $this->dbsType, $this->db, $this->fieldConf);
		if ($this->dbsType=='sql') {
			$qtable = $this->db->quotekey($this->table);
			if (isset($options['order']) && $this->db->driver() == 'pgsql')
				// PostgreSQLism: sort NULL values to the end of a table
				$options['order'] = preg_replace('/\h+DESC(?=\s*(?:$|,))/i',' DESC NULLS LAST',$options['order']);
			// assemble full sql query for joined queries
			if ($hasJoin) {
				// when in count-mode and grouping is active, wrap the query later
				// otherwise add a an adhoc counter field here
				if (!($subquery_mode=($options && !empty($options['group']))) && $count)
					$this->adhoc['_rows']=['expr'=>'COUNT(*)','value'=>NULL];
				$adhoc=[];
				if (!$count)
					// add bind parameters for filters in adhoc fields
					if ($this->preBinds) {
						$crit = array_shift($filter);
						$filter = array_merge($this->preBinds,$filter);
						array_unshift($filter,$crit);
					}
				if (!empty($m_refl_adhoc))
					// add adhoc field expressions
					foreach ($m_refl_adhoc as $key=>$val)
						$adhoc[]=$val['expr'].' AS '.$this->db->quotekey($key);
				$fields=implode(',',$adhoc);
				if ($count && $subquery_mode) {
					if (empty($fields))
						// Select at least one field, ideally the grouping fields or sqlsrv fails
						$fields=preg_replace('/HAVING.+$/i','',$options['group']);
					if (preg_match('/mssql|dblib|sqlsrv/',$this->engine))
						$fields='TOP 100 PERCENT '.$fields;
				}
				if (!$count)
					// add only selected fields to field list
					$fields.=($fields?', ':'').implode(', ',array_map(function($field) use($qtable){
						return $qtable.'.'.$this->db->quotekey($field);
					},array_diff($this->mapper->fields(),array_keys($m_refl_adhoc))));
				// assemble query
				$sql = 'SELECT '.$fields.' FROM '.$qtable.' '
					.implode(' ',$hasJoin).' WHERE '.$filter[0];
				$db=$this->db;
				// add grouping in both, count & selection mode
				if (isset($options['group']))
					$sql.=' GROUP BY '.preg_replace_callback('/\w+[._\-\w]*/i',
						function($match) use($db) {
							return $db->quotekey($match[0]);
						}, $options['group']);
				if (!$count) {
					if (isset($options['order']))
						$sql.=' ORDER BY '.implode(',',array_map(
							function($str) use($db) {
								return preg_match('/^\h*(\w+[._\-\w]*)(?:\h+((?:ASC|DESC)[\w\h]*))?\h*$/i',
									$str,$parts)?
									($db->quotekey($parts[1]).
										(isset($parts[2])?(' '.$parts[2]):'')):$str;
							},
							explode(',',$options['order'])));
					// SQL Server fixes
					if (preg_match('/mssql|sqlsrv|odbc/', $this->db->driver()) &&
						(isset($options['limit']) || isset($options['offset']))) {
						$ofs=isset($options['offset'])?(int)$options['offset']:0;
						$lmt=isset($options['limit'])?(int)$options['limit']:0;
						if (strncmp($this->db->version(),'11',2)>=0) {
							// SQL Server >= 2012
							if (!isset($options['order']))
								$sql.=' ORDER BY '.$this->db->quotekey($this->primary);
							$sql.=' OFFSET '.$ofs.' ROWS'.($lmt?' FETCH NEXT '.$lmt.' ROWS ONLY':'');
						} else {
							// SQL Server 2008
							$order=(!isset($options['order']))
								?($this->db->quotekey($this->table.'.'.$this->primary)):$options['order'];
							$sql=str_replace('SELECT','SELECT '.($lmt>0?'TOP '.($ofs+$lmt):'').' ROW_NUMBER() '.
								'OVER (ORDER BY '.$order.') AS rnum,',$sql);
							$sql='SELECT * FROM ('.$sql.') x WHERE rnum > '.($ofs);
						}
					} else {
						if (isset($options['limit']))
							$sql.=' LIMIT '.(int)$options['limit'];
						if (isset($options['offset']))
							$sql.=' OFFSET '.(int)$options['offset'];
					}
				} elseif ($subquery_mode)
					// wrap count query if necessary
					$sql='SELECT COUNT(*) AS '.$this->db->quotekey('_rows').' '.
						'FROM ('.$sql.') AS '.$this->db->quotekey('_temp');
				unset($filter[0]);
				$result = $this->db->exec($sql, $filter, $ttl);
				if ($count)
					return $result[0]['_rows'];
				foreach ($result as &$record) {
					// factory new mappers
					$mapper = clone($this->mapper);
					$mapper->reset();
					$mapper->query= array($record);
					foreach ($record as $key=>$val)
						$mapper->set($key, $val);
					$record = $mapper;
					unset($record, $mapper);
				}
				return $result;
			} elseif (!empty($this->preBinds)) {
				// bind values to adhoc queries
				if (!$filter)
					// we (PDO) need any filter to bind values
					$filter = array('1=1');
				$crit = array_shift($filter);
				$filter = array_merge($this->preBinds,$filter);
				array_unshift($filter,$crit);
			}
		}
		if ($options) {
			$options = $this->queryParser->prepareOptions($options,$this->dbsType,$this->db);
			if ($count)
				unset($options['order']);
		}
		return ($count)
			? $this->mapper->count($filter,$options,$ttl)
			: $this->mapper->find($filter,$options,$ttl);
	}
1305132
@Override
    public EntityIdentifier[] searchForGroups(
            final String query,
            final SearchMethod method,
            @SuppressWarnings("unchecked") final Class leaftype) {

        // only search for groups
        if (leaftype != IPerson.class) {
            return new EntityIdentifier[] {};
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Searching Grouper for groups matching query: " + query);
        }

        // result groups.
        List<EntityIdentifier> groups = new ArrayList<EntityIdentifier>();

        try {

            // TODO: searches need to be performed against the group display
            // name rather than the group key

            GcFindGroups groupSearch = new GcFindGroups();
            WsQueryFilter filter = new WsQueryFilter();
            // is this an exact search or fuzzy
            if ((method == SearchMethod.DISCRETE_CI) || (method == SearchMethod.DISCRETE)) {
                filter.setQueryFilterType("FIND_BY_GROUP_NAME_EXACT");
            } else {
                filter.setQueryFilterType("FIND_BY_GROUP_NAME_APPROXIMATE");
            }
            filter.setGroupName(query);
            groupSearch.assignQueryFilter(filter);
            WsFindGroupsResults results = groupSearch.execute();

            if (results != null && results.getGroupResults() != null) {
                for (WsGroup g : results.getGroupResults()) {
                    if (validKey(g.getName())) {
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace("Retrieved group: " + g.getName());
                        }
                        groups.add(new EntityIdentifier(g.getName(), IEntityGroup.class));
                    }
                }
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Returning " + groups.size() + " results for query " + query);
            }

            return groups.toArray(new EntityIdentifier[groups.size()]);

        } catch (Exception e) {
            LOGGER.warn(
                    "Exception while attempting to retrieve "
                            + "search results for query "
                            + query
                            + " and entity type "
                            + leaftype.getCanonicalName()
                            + " : "
                            + e.getMessage());
            return new EntityIdentifier[] {};
        }
    }
1018768
public function findForPaginateFilterBySiteIds(PaginateFinderConfiguration $configuration, $language, array $siteIds)
    {
        $qa = $this->createAggregationQuery();

        $this->filterSearchAndSiteIds($configuration, $language, $siteIds, $qa);

        $order = $configuration->getOrder();
        if (!empty($order)) {
            $qa->sort($order);
        }

        $qa->skip($configuration->getSkip());
        $qa->limit($configuration->getLimit());

        return $this->hydrateAggregateQuery($qa);
    }
564477
public function returnFilteredEntities(QueryBuilder $builder, AbstractFilter $filter, $groupBy) {
        $pagination = $filter->getPagination();

        if ($pagination->getLimit()) {
            $builder->setMaxResults($pagination->getLimit());
        }
        $builder->setFirstResult($pagination->getOffset());

        if ($pagination->isEnabled()) {
            $query = $builder->getQuery();
            $query->setHydrationMode($filter->getHydrationMode());
            $paginator = new Paginator($query, true);
            $pagination->setTotalResults(count($paginator));
            return $paginator;
        }

        $builder->groupBy($groupBy);
        $query    = $builder->getQuery();
        $entities = $query->getResult($filter->getHydrationMode());
        return $entities;
    }
441748
public function filter($content, $search, $type)
    {
        $items = !empty($content) ? unserialize($content) : [];
        switch ($type) {
            case 'in':
                foreach ($items as $item) {
                    if (strpos($item, $search) !== false) {
                        return true;
                    }
                }
                return false;
                break;
            default:
                return in_array($search, $items);
        }
    }
1258681
public function findByGroupName($groupName)
    {
        return $this->searchForOneNode(
            $this->buildFilter(
                new Filter\StringFilter($this->connection->getConfiguration()->getGroupNameAttribute() . '=' . Filter\AbstractFilter::escapeValue($groupName))
            )
        );
    }
892401
public function getEntries($search)
    {
        $entries = ldap_get_entries($this->connect, $search);

        array_walk_recursive($entries, function (&$item) {
            if (!mb_detect_encoding($item, 'utf-8', true)) {
                $item = utf8_encode($item);
            }
        });

        return $entries;
    }
1282318
public function findByNameAndGroup(
        $search,
        Group $group,
        $executeQuery = true,
        $orderedBy = 'id',
        $order = 'ASC'
    )
    {
        $dql = "
            SELECT DISTINCT u FROM Claroline\CoreBundle\Entity\User u
            JOIN u.groups g
            WHERE g.id = :groupId
            AND (UPPER(u.username) LIKE :search
            OR UPPER(u.lastName) LIKE :search
            OR UPPER(u.firstName) LIKE :search)
            AND u.isEnabled = true
            ORDER BY u.{$orderedBy} {$order}
        ";
        $upperSearch = strtoupper($search);
        $query = $this->_em->createQuery($dql);
        $query->setParameter('search', "%{$upperSearch}%");
        $query->setParameter('groupId', $group->getId());

        return $executeQuery ? $query->getResult() : $query;
    }
122236
public function createFilter($search, $replace)
    {
        if (!isset($this->filters[$search][$replace])) {
            if (!isset($this->filters[$search])) {
                $this->filters[$search] = [];
            }

            if (!isset($this->filters[$search][$replace])) {
                $this->filters[$search][$replace] = [];
            }

            $this->filters[$search][$replace] = new Swift_StreamFilters_StringReplacementFilter($search, $replace);
        }

        return $this->filters[$search][$replace];
    }
112723
public function searchFilter($searchFilters, $options = [])
    {
        $_options = [];

        $options = array_merge($_options, $options);

        return ($searchFilters ? $this->Search->filterForm($searchFilters) : null);
    }
1034771
public function findAllByLocale($locale, $filter = array())
    {
        if (empty($filter)) {
            $items = $this->itemRepository->findAllByLocale($locale);
        } else {
            $items = $this->itemRepository->findByLocaleAndFilter($locale, $filter);
        }

        array_walk(
            $items,
            function (&$item) use ($locale) {
                $item = $this->itemFactory->createApiEntity($item, $locale);
            }
        );

        return $items;
    }
903517
public function search($term, $host = null, $locale = null)
    {
        $qb = $this->createQueryBuilder('c');

        $results = $qb
            ->innerjoin('c.blocks', 'b', 'WITH', 'c.id = b.content')
            ->leftJoin('c.site', 'os')
            ->leftJoin('os.domains', 'd')
            ->where($qb->expr()->orX(
                $qb->expr()->like('c.title', ':term'),
                $qb->expr()->like('c.description', ':term'),
                $qb->expr()->like('b.value', ':term')
            ))
            ->andWhere('c.searchable = :searchable')
            ->andWhere('c.active = :active')
            ->andWhere('c.layout = :layout')
            ->andWhere('d.domain = :host OR c.site IS NULL')
            ->andWhere('c.locale = :locale OR c.locale IS NULL')
            ->setParameter('term', '%'.$term.'%')
            ->setParameter('searchable', true)
            ->setParameter('active', true)
            ->setParameter('layout', false)
            ->setParameter('host', $host)
            ->setParameter('locale', $locale)
            ->groupBy('c.id')
            ->orderBy('c.id')
            ->getQuery()
            ->getResult();

        return $this->sortSearchResults($results, $term);
    }
793455
public function load($locale, $group, $namespace = null)
    {
        $results = [];
        foreach ($this->loaders as $loader) {
            $results = array_merge($results, $loader->load($locale, $group, $namespace));
        }

        return $results;
    }
1092893
protected function createSearch(Search $search, array $filters, $locale)
    {
        if (0 < count($filters['excluded'])) {
            foreach ($filters['excluded'] as $uuid) {
                $search->addQuery(new TermQuery('uuid', $uuid), BoolQuery::MUST_NOT);
            }
        }

        $query = new BoolQuery();

        $queriesCount = 0;
        $operator = $this->getFilter($filters, 'tagOperator', 'or');
        $this->addBoolQuery('tags', $filters, 'excerpt.tags.id', $operator, $query, $queriesCount);
        $operator = $this->getFilter($filters, 'websiteTagsOperator', 'or');
        $this->addBoolQuery('websiteTags', $filters, 'excerpt.tags.id', $operator, $query, $queriesCount);

        $operator = $this->getFilter($filters, 'categoryOperator', 'or');
        $this->addBoolQuery('categories', $filters, 'excerpt.categories.id', $operator, $query, $queriesCount);
        $operator = $this->getFilter($filters, 'websiteCategoriesOperator', 'or');
        $this->addBoolQuery('websiteCategories', $filters, 'excerpt.categories.id', $operator, $query, $queriesCount);

        if (null !== $locale) {
            $search->addQuery(new TermQuery('locale', $locale));
        }

        if (array_key_exists('types', $filters) && $filters['types']) {
            $typesQuery = new BoolQuery();
            foreach ($filters['types'] as $typeFilter) {
                $typesQuery->add(new TermQuery('type', $typeFilter), BoolQuery::SHOULD);
            }
            $search->addQuery($typesQuery);
        }

        if (array_key_exists('structureTypes', $filters) && $filters['structureTypes']) {
            $strTypesQuery = new BoolQuery();
            foreach ($filters['structureTypes'] as $filter) {
                $strTypesQuery->add(new TermQuery('structure_type', $filter), BoolQuery::SHOULD);
            }
            $search->addQuery($strTypesQuery);
        }

        if (0 === $queriesCount) {
            $search->addQuery(new MatchAllQuery(), BoolQuery::MUST);
        } else {
            $search->addQuery($query, BoolQuery::MUST);
        }

        return $search;
    }