Find assets by title or given tags

@param string $searchTerm
@param array $tags
@param AssetCollection $assetCollection
@return QueryResultInterface
@throws InvalidQueryException
421026
public function findBySearchTermOrTags($searchTerm, array $tags = [], AssetCollection $assetCollection = null)
    {
        $query = $this->createQuery();

        $constraints = [
            $query->like('title', '%' . $searchTerm . '%'),
            $query->like('resource.filename', '%' . $searchTerm . '%'),
            $query->like('caption', '%' . $searchTerm . '%')
        ];
        foreach ($tags as $tag) {
            $constraints[] = $query->contains('tags', $tag);
        }
        $query->matching($query->logicalOr($constraints));
        $this->addImageVariantFilterClause($query);
        $this->addAssetCollectionToQueryConstraints($query, $assetCollection);
        return $query->execute();
    }
349270
public function loadMediaMatchAll($tags = [])
    {
        $tags = (array) $tags;
        $closure = function (MorphToMany $q) use ($tags) {
            $this->addMatchAllToEagerLoadQuery($q, $tags);
        };
        $closure = Closure::bind($closure, $this->first(), $this->first());

        return $this->load(['media' => $closure]);
    }
981126
private function getSearchResult(array $filters, $limit, $page, $pageSize, $locale, $webspaceKey)
    {
        $repository = $this->searchManager->getRepository($this->articleDocumentClass);
        $search = $this->createSearch($repository->createSearch(), $filters, $locale);
        if (!$search) {
            return new \ArrayIterator([]);
        }

        $this->addPagination($search, $pageSize, $page, $limit);

        if (array_key_exists('sortBy', $filters) && is_array($filters['sortBy'])) {
            $sortMethod = array_key_exists('sortMethod', $filters) ? $filters['sortMethod'] : 'asc';
            $this->appendSortBy($filters['sortBy'], $sortMethod, $search);
        }

        if ($webspaceKey) {
            $webspaceQuery = new BoolQuery();

            // check for mainWebspace
            $webspaceQuery->add(new TermQuery('main_webspace', $webspaceKey), BoolQuery::SHOULD);

            // check for additionalWebspaces
            $webspaceQuery->add(new TermQuery('additional_webspaces', $webspaceKey), BoolQuery::SHOULD);

            $search->addQuery($webspaceQuery);
        }

        return $repository->findDocuments($search);
    }
1040717
public function findAdminChildrenFromTags(array $tags)
    {
        if (count($tags) === 0) {
            throw new \InvalidArgumentException('Array argument cannot be empty');
        }

        $index = 0;
        $eol = PHP_EOL;
        $tagsTest = '(';

        foreach ($tags as $tag) {
            $tagsTest .= $index > 0 ? '    OR ' : '    ';
            $tagsTest .= "p.id = {$tag}{$eol}";
            $index++;
        }
        $tagsTest .= "){$eol}";

        $dql = "
            SELECT DISTINCT t
            FROM Claroline\CoreBundle\Entity\Workspace\WorkspaceTag t
            WHERE t.user IS NULL
            AND EXISTS (
                SELECT h
                FROM Claroline\CoreBundle\Entity\Workspace\WorkspaceTagHierarchy h
                JOIN h.parent p
                WHERE h.user IS NULL
                AND h.tag = t
                AND {$tagsTest}
            )
            ORDER BY t.name
        ";
        $query = $this->_em->createQuery($dql);

        return $query->getResult();
    }
907614
public static function findByName($tags, string $group = null, string $locale = null): Collection
    {
        $locale = $locale ?? app()->getLocale();

        return collect(Taggable::parseDelimitedTags($tags))->map(function (string $tag) use ($group, $locale) {
            return ($exists = static::firstByName($tag, $group, $locale)) ? $exists->getKey() : null;
        })->filter()->unique();
    }
1080136
public function indexSearch($searchText, $maxResults)
    {
        // split the phrase into words
        $words = SearchAnalyser::analyse($searchText);
        if (!$words) {
            return [];
        }

        $query = $this->_em->createQueryBuilder()
            ->select('o')
            ->from($this->_entityName, 'o')
            ->setMaxResults($maxResults);

        $parameters = [];
        foreach ($words as $k => $word) {
            $subquery = $this->_em->createQueryBuilder()
                ->select("i$k.keyword")
                ->from($this->getSearchIndexClass(), "i$k")
                ->where("i$k.object = o")
                ->andWhere("i$k.keyword ILIKE :search$k");
            $query->andWhere($query->expr()->exists($subquery->getDql()));
            $parameters["search$k"] = '%' . $word . '%';
        }
        $query->setParameters($parameters);

        $results = $query->getQuery()->execute();

        return $results;
    }
396727
public function searchPosts(
        array $tags,
        int $page,
        int $limit = 20
    ): array {
        return Post::search($this, $tags, $page, $limit);
    }
1120837
protected function createQueryForTags(array $tags)
    {
        $databaseConnection = self::getDatabaseConnection('tx_kesearch_index');
        $where = '';
        if (count($tags) && is_array($tags)) {
            foreach ($tags as $value) {
                // @TODO: check if this works as intended / search for better way
                $value = $databaseConnection->quote($value);
                $value = rtrim($value, "'");
                $value = ltrim($value, "'");
                $where .= ' AND MATCH (tags) AGAINST (\'' . $value . '\' IN BOOLEAN MODE) ';
            }
            return $where;
        }
        return '';
    }
510300
public function getFiltered($page, $numRows, $sortAttr, $sortOrder, $searchAttr, $searchValue, $richFilters = [])
    {
        $query = $this->prepareQuery();

        $query = $this->richFiltersOnQuery($query, $richFilters);

        if ($sortAttr && $sortOrder && $this->inScope($sortAttr)) {
            $scope = $this->getScope($sortAttr);
            $query = $query->orderBy($scope, $sortOrder);
        }

        if ($searchAttr && $searchValue && $this->inScope($searchAttr)) {
            $scope = $this->getScope($searchAttr);
            $query = $query->where($scope, 'like', '%' . $searchValue . '%');
        }

        $collection = $query->get();

        $collection = $this->addPermissions($collection);

        $collection = $this->formatCollection($collection);

        $collection = $collection->each(function ($model) {
            $model = $this->formatModel($model);
        });

        if ($sortAttr && $sortOrder && ! $this->inScope($sortAttr)) {
            $collection = $sortOrder == 'asc'
                ? $collection->sortBy($sortAttr)
                : $collection->sortByDesc($sortAttr);
        }

        $collection = $this->richFiltersOnCollection($collection, $richFilters);

        if ($searchAttr && $searchValue && ! $this->inScope($searchAttr)) {
            $collection = $collection->filter(function ($model) use ($searchAttr, $searchValue) {
                $value = (string) $model->$searchAttr;
                $value = strtolower($value);
                $search = strtolower($searchValue);
                return strpos($value, $search) !== false;
            });
        }

        if ($page && $numRows) {
            $toSkip = ($page - 1) * $numRows;
            $count = $collection->count();
            $collection = $collection->take(- ($count - $toSkip))->take($numRows);
        } else if ($numRows)
            $collection = $collection->take($numRows);

        return collect(array_values($collection->toArray()));
    }
1176273
protected function whereTag($query, EntryQueryOptions $options)
    {
        $query->when($options->tag, function ($query, $tag) {
            return $query->whereIn('uuid', function ($query) use ($tag) {
                $query->select('entry_uuid')->from('telescope_entries_tags')->whereTag($tag);
            });
        });

        return $this;
    }
1021650
public function selectByTags(array $tags)
    {
        $result = [];
        foreach ($this->array['Key2Tags'] as $key => $keyTags) {
            $found = true;
            foreach ($tags as $t) {
                if (array_search($t, $keyTags)===false) {
                    $found = false;
                }
            }

            if ($found) {
                $result[] = $key;
            }
        }

        return $result;
    }
1234464
public function scopeWithAnyTags(Builder $query, $tags, string $type = null): Builder
    {
        $tags = static::convertToTags($tags, $type);

        return $query->whereHas('tags', function (Builder $query) use ($tags) {
            $tagIds = collect($tags)->pluck('id');

            $query->whereIn('tags.id', $tagIds);
        });
    }
405858
public function tag_search_page($query = '', $tagcollid = 0) {
        $rv = $this->output->heading(get_string('searchtags', 'tag'), 2);

        $searchbox = $this->search_form($query, $tagcollid);
        $rv .= html_writer::div($searchbox, '', array('id' => 'tag-search-box'));

        $tagcloud = core_tag_collection::get_tag_cloud($tagcollid, false, 150, 'name', $query);
        $searchresults = '';
        if ($tagcloud->get_count()) {
            $searchresults = $this->output->render_from_template('core_tag/tagcloud',
                    $tagcloud->export_for_template($this->output));
            $rv .= html_writer::div($searchresults, '', array('id' => 'tag-search-results'));
        } else if (strval($query) !== '') {
            $rv .= '<div class="tag-search-empty">' . get_string('notagsfound', 'tag', s($query)) . '</div>';
        }

        return $rv;
    }
247649
def query_tags(tags, hrefs=nil, timeout=120)
      cmd = { :name => :query_tags, :tags => tags }
      cmd[:hrefs] = hrefs unless hrefs.nil? || hrefs.empty?
      response = blocking_request(cmd, timeout)
      begin
        result = OperationResult.from_results(load(response, "Unexpected response #{response.inspect}"))
        raise TagError.new("Query tags failed: #{result.content}") unless result.success?
        return result.content
      rescue
        raise TagError.new("Query tags failed: #{response.inspect}")
      end
    end
1214782
public function search(string $query, array $arguments = null)
    {
        $args = ['q' => $query];
        if (is_array($arguments)) {
            $args = array_merge($arguments, $args);
        }
        return new SearchIterator($this, 'search/tweets', $args);
    }
908458
public function scopeWithAllTags(Builder $query, $tags)
    {
        $tags = static::convertToTags($tags);

        $tags->each(function ($tag) use ($query) {
            $query->whereHas('tags', function (Builder $query) use ($tag) {
                return $query->where('id', $tag ? $tag->id : 0);
            });
        });

        return $query;
    }
899880
public function scopeWithAnyTag($query, $tagNames)
	{
		if(!is_array($tagNames)) {
			$tagNames = func_get_args();
			array_shift($tagNames);
		}
		$tagNames = static::$taggingUtility->makeTagArray($tagNames);

		$model = static::$taggingUtility->tagModelString();
		$tagids = $model::byTagNames($tagNames)->lists('id')->all();

		$className = $query->getModel()->getMorphClass();
		$primaryKey = $this->getKeyName();

		$tags = Tagged::whereIn('tag_id', $tagids)
			->where('taggable_type', $className)
			->lists('taggable_id');

		return $query->whereIn($this->getTable().'.'.$primaryKey, $tags);
	}