Execute search.

@param \Magento\Framework\Api\Search\SearchCriteriaInterface $searchCriteria Search criteria.

@return \Magento\Framework\Api\Search\SearchResultInterface
760030
public function search(\Magento\Framework\Api\Search\SearchCriteriaInterface $searchCriteria)
    {
        $searchRequest  = $this->searchRequestBuilder->getRequest($searchCriteria);
        $searchResponse = $this->searchEngine->search($searchRequest);
        $searchResult   = $this->searchResponseBuilder->build($searchResponse);

        $totalCount = $searchResponse->count();
        $searchResult->setTotalCount($totalCount);
        $searchResult->setSearchCriteria($searchCriteria);

        return $searchResult;
    }
674801
protected function addSort(array $sortCriteria) {
        $sort = '';

        $orderOperator = [
            'asc' => $this->getDriverEscaper()->dbCommand('ASC'),
            'desc' => $this->getDriverEscaper()->dbCommand('DESC'),
        ];

        if (count($sortCriteria) > 0) {
            $sort = $this->getDriverEscaper()->dbCommand('ORDER BY');
            $crirerias = [];
            
            foreach ($sortCriteria as $field => $order) {
                if(array_key_exists($order, $orderOperator)) {
                    $crirerias[] = ' ' . $this->getDriverEscaper()->reserved($field) . ' ' . $orderOperator[$order] . ' ';
                } else {
                    throw new QueryParsingException();
                }
            }
            $sort .= implode($this->getDriverEscaper()->getFieldsSeparator(), $crirerias);
        }

        return $sort;
    }
314419
public function query($name, QueryObjectInterface $queryObject, DisplayCriteriaInterface $displayCriteria = null)
    {
        $result = $this->doQuery($queryObject, $displayCriteria);
        $this->data[$name] = $result;

        return $result;
    }
366476
public function init(BaseModelCriteria $criteria, DataFetcherInterface $dataFetcher = null)
    {
        $this->dbName = $criteria->getDbName();
        $this->setClass($criteria->getModelName());
        $this->setWith($criteria->getWith());
        $this->asColumns = $criteria->getAsColumns();
        $this->hasLimit = $criteria->getLimit() != -1;
        if ($dataFetcher) {
            $this->setDataFetcher($dataFetcher);
        }

        return $this;
    }
1006884
protected function getContents($searchCriterias)
    {
        $searchCriterias = array_merge(array(
            'contentType' => '',
            'choiceType' => ReadContentRepositoryInterface::CHOICE_AND,
            'keywords' => null,
        ), $searchCriterias);
        $language = $this->currentSiteManager->getSiteLanguage();
        $siteId = $this->currentSiteManager->getSiteId();

        return $this->contentRepository->findByContentTypeAndCondition($language, $searchCriterias['contentType'], $searchCriterias['choiceType'], $searchCriterias['keywords'], $siteId);
    }
846064
public function criteria(Criteria\Criteria $cri = null)
    {
        if (! $cri) $cri = new Criteria\Criteria($this);
        $cri->setTable($this);

        return $cri;
    }
886576
protected function setSearchCriteriaFromQuery()
    {
        $this->initSearchCriteria();

        foreach ($this->aCriteria as $sIndex => $mValue) {
            $this->aCriteria[$sIndex] = $this->app['request']->query->get($sIndex, $mValue);
        }
    }
216631
public function getFiltersComponent(SearchQuery $searchQuery)
    {
        $criteriaComponent = $this->getCriteriaComponent($searchQuery);

        $components = array_merge(
            $this->getRequireFiltersComponent($searchQuery),
            $this->getExcludeFiltersComponent($searchQuery)
        );

        if ($criteriaComponent !== null) {
            $components[] = $criteriaComponent;
        }

        return $components;
    }
511633
private function applyCriteriaToQueryBuilder(Criteria $criteria, QueryBuilder $qb, $prefix)
    {
        if ($criteria->getMode() === Criteria::MODE_OR) {
            $expr = $qb->expr()->orX();
        } else {
            $expr = $qb->expr()->andX();
        }
        foreach ($criteria as $criterium) {
            if ($criterium instanceof Criteria) {
                $expr->add(
                    $this->applyCriteriaToQueryBuilder($criterium, $qb, $prefix)
                );
            } else {
                $this->applyCriteriumToQueryBuilder($criterium, $qb, $expr, $prefix);
            }
        }

        return $expr;
    }
721392
public function search_courses($searchcriteria) {
        global $CFG;
        $content = '';
        if (!empty($searchcriteria)) {
            // print search results

            $displayoptions = array('sort' => array('displayname' => 1));
            // take the current page and number of results per page from query
            $perpage = optional_param('perpage', 0, PARAM_RAW);
            if ($perpage !== 'all') {
                $displayoptions['limit'] = ((int)$perpage <= 0) ? $CFG->coursesperpage : (int)$perpage;
                $page = optional_param('page', 0, PARAM_INT);
                $displayoptions['offset'] = $displayoptions['limit'] * $page;
            }
            // options 'paginationurl' and 'paginationallowall' are only used in method coursecat_courses()
            $displayoptions['paginationurl'] = new moodle_url('/course/search.php', $searchcriteria);
            $displayoptions['paginationallowall'] = true; // allow adding link 'View all'

            $class = 'course-search-result';
            foreach ($searchcriteria as $key => $value) {
                if (!empty($value)) {
                    $class .= ' course-search-result-'. $key;
                }
            }
            $chelper = new coursecat_helper();
            $chelper->set_show_courses(self::COURSECAT_SHOW_COURSES_EXPANDED_WITH_CAT)->
                    set_courses_display_options($displayoptions)->
                    set_search_criteria($searchcriteria)->
                    set_attributes(array('class' => $class));

            $courses = core_course_category::search_courses($searchcriteria, $chelper->get_courses_display_options());
            $totalcount = core_course_category::search_courses_count($searchcriteria);
            $courseslist = $this->coursecat_courses($chelper, $courses, $totalcount);

            if (!$totalcount) {
                if (!empty($searchcriteria['search'])) {
                    $content .= $this->heading(get_string('nocoursesfound', '', $searchcriteria['search']));
                } else {
                    $content .= $this->heading(get_string('novalidcourses'));
                }
            } else {
                $content .= $this->heading(get_string('searchresults'). ": $totalcount");
                $content .= $courseslist;
            }

            if (!empty($searchcriteria['search'])) {
                // print search form only if there was a search by search string, otherwise it is confusing
                $content .= $this->box_start('generalbox mdl-align');
                $content .= $this->course_search_form($searchcriteria['search']);
                $content .= $this->box_end();
            }
        } else {
            // just print search form
            $content .= $this->box_start('generalbox mdl-align');
            $content .= $this->course_search_form();
            $content .= $this->box_end();
        }
        return $content;
    }
472644
protected function sort(ModelCriteria $query, Request $request)
    {
        $order = $this->getSortOrder($request);

        foreach ($order as $setting) {
            $column = $setting[0];
            $direction = $setting[1];
            $query->orderBy($column, $direction);
        }

        return $query;
    }
130850
private function getCurrentCategoryId(ContainerConfigurationInterface $containerConfiguration, SearchCriteriaInterface $searchCriteria)
    {
        $store      = $this->storeManager->getStore($containerConfiguration->getStoreId());
        $categoryId = $this->storeManager->getGroup($store->getStoreGroupId())->getRootCategoryId();

        foreach ($searchCriteria->getFilterGroups() as $filterGroup) {
            foreach ($filterGroup->getFilters() as $filter) {
                if ($filter->getField() == "category_ids") {
                    $categoryId = $filter->getValue();
                }
            }
        }

        return $categoryId;
    }
1183220
protected function searchWithOffset(ModelCriteria $search)
    {
        $limit = (int) $this->getArgValue('limit');

        if ($limit >= 0) {
            $search->limit($limit);
        }

        $search->offset((int) $this->getArgValue('offset'));

        return $search->find();
    }
1121212
private function prepareNormalSql(array $searchCriteria, string $classname, string $andOr, int $fKey): string
    {
        $sql = '';
        $textFields = $this->getTextFields($classname);
        list($searchField, $operator, $searchValues) = $searchCriteria;
        $operator = $this->operators[$operator];

        if (trim($searchValues) !== '') {
            if ($searchValues == '%%') {
                $sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' IS NULL';
                $sql .= ' OR ' . $classname . '.' . $searchField . ' = ""';

                if ($this->model->$searchField === 0) {
                    $sql .= ' OR ' . $classname . '.' . $searchField . ' = 0';
                }

                $sql .= ')';
            } elseif ($searchValues == '$$') {
                $sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' IS NOT NULL';
                $sql .= ' OR ' . $classname . '.' . $searchField . ' != ""';

                if ($this->model->$searchField === 0) {
                    $sql .= ' OR ' . $classname . '.' . $searchField . ' != 0';
                }

                $sql .= ')';
            } else {
                if (strpos($searchValues, '|')) {
                    $searchValues = explode('|', $searchValues);
                } else {
                    $searchValues = [$searchValues];
                }

                foreach ($searchValues as $vKey => $value) {
                    if ((in_array($searchField, $textFields)
                        && preg_match('#^%[^%]+%|%[^%]+|[^%]+%$#i', $value))
                        || $value == '%%'
                    ) {
                        $operator = 'LIKE';
                    }

                    if (!$vKey) {
                        $sql .= ' ' . $andOr . ' (' . $classname . '.' . $searchField . ' ' . $operator . ' :f' . $searchField . $fKey . $vKey;
                    } else {
                        $sql .= ' OR ' . $classname . '.' . $searchField . ' ' . $operator . ' :f' . $searchField . $fKey . $vKey;
                    }

                    $this->bindParamsKeys[] = 'f' . $searchField . $fKey . $vKey;
                    $this->bindParamsValues[] = $value;
                }

                $sql .= ')';
            }
        }

        return $sql;
    }
468814
private function openCriteria(array &$criteria, $connector = self::LOGICAL_AND)
    {
        $criteria[] = array('bracket' => self::BRACKET_OPEN,
            'connector' => $connector);

        return $this;
    }
292247
public function search( Form $form, SearchCriteriaBuilder $searchCriteriaBuilder, SearchResultConverter $resultConverter, $offset, $length, $params = array() ) {

        $criteria = $searchCriteriaBuilder->build($form, $offset, $length, $params);

        $searchResults = $this->repository->getSearchService()->findContent( $criteria );

        return $resultConverter->convert( $searchResults );
    }
248987
public function execute() {
        global $CFG, $COMPLETION_CRITERIA_TYPES, $DB;

        if ($CFG->enablecompletion) {
            require_once($CFG->libdir . "/completionlib.php");

            // Process each criteria type.
            foreach ($COMPLETION_CRITERIA_TYPES as $type) {
                $object = 'completion_criteria_' . $type;
                require_once($CFG->dirroot . '/completion/criteria/' . $object . '.php');

                $class = new $object();
                // Run the criteria type's cron method, if it has one.
                if (method_exists($class, 'cron')) {
                    if (debugging()) {
                        mtrace('Running '.$object.'->cron()');
                    }
                    $class->cron();
                }
            }

            if (debugging()) {
                mtrace('Aggregating completions');
            }

            // Save time started.
            $timestarted = time();

            // Grab all criteria and their associated criteria completions.
            $sql = 'SELECT DISTINCT c.id AS course, cr.id AS criteriaid, crc.userid AS userid,
                                    cr.criteriatype AS criteriatype, cc.timecompleted AS timecompleted
                      FROM {course_completion_criteria} cr
                INNER JOIN {course} c ON cr.course = c.id
                INNER JOIN {course_completions} crc ON crc.course = c.id
                 LEFT JOIN {course_completion_crit_compl} cc ON cc.criteriaid = cr.id AND crc.userid = cc.userid
                     WHERE c.enablecompletion = 1
                       AND crc.timecompleted IS NULL
                       AND crc.reaggregate > 0
                       AND crc.reaggregate < :timestarted
                  ORDER BY course, userid';
            $rs = $DB->get_recordset_sql($sql, ['timestarted' => $timestarted]);

            // Check if result is empty.
            if (!$rs->valid()) {
                $rs->close();
                return;
            }

            $currentuser = null;
            $currentcourse = null;
            $completions = [];
            while (1) {
                // Grab records for current user/course.
                foreach ($rs as $record) {
                    // If we are still grabbing the same users completions.
                    if ($record->userid === $currentuser && $record->course === $currentcourse) {
                        $completions[$record->criteriaid] = $record;
                    } else {
                        break;
                    }
                }

                // Aggregate.
                if (!empty($completions)) {
                    if (debugging()) {
                        mtrace('Aggregating completions for user ' . $currentuser . ' in course ' . $currentcourse);
                    }

                    // Get course info object.
                    $info = new \completion_info((object)['id' => $currentcourse]);

                    // Setup aggregation.
                    $overall = $info->get_aggregation_method();
                    $activity = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ACTIVITY);
                    $prerequisite = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_COURSE);
                    $role = $info->get_aggregation_method(COMPLETION_CRITERIA_TYPE_ROLE);

                    $overallstatus = null;
                    $activitystatus = null;
                    $prerequisitestatus = null;
                    $rolestatus = null;

                    // Get latest timecompleted.
                    $timecompleted = null;

                    // Check each of the criteria.
                    foreach ($completions as $params) {
                        $timecompleted = max($timecompleted, $params->timecompleted);
                        $completion = new \completion_criteria_completion((array)$params, false);

                        // Handle aggregation special cases.
                        if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ACTIVITY) {
                            completion_cron_aggregate($activity, $completion->is_complete(), $activitystatus);
                        } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_COURSE) {
                            completion_cron_aggregate($prerequisite, $completion->is_complete(), $prerequisitestatus);
                        } else if ($params->criteriatype == COMPLETION_CRITERIA_TYPE_ROLE) {
                            completion_cron_aggregate($role, $completion->is_complete(), $rolestatus);
                        } else {
                            completion_cron_aggregate($overall, $completion->is_complete(), $overallstatus);
                        }
                    }

                    // Include role criteria aggregation in overall aggregation.
                    if ($rolestatus !== null) {
                        completion_cron_aggregate($overall, $rolestatus, $overallstatus);
                    }

                    // Include activity criteria aggregation in overall aggregation.
                    if ($activitystatus !== null) {
                        completion_cron_aggregate($overall, $activitystatus, $overallstatus);
                    }

                    // Include prerequisite criteria aggregation in overall aggregation.
                    if ($prerequisitestatus !== null) {
                        completion_cron_aggregate($overall, $prerequisitestatus, $overallstatus);
                    }

                    // If aggregation status is true, mark course complete for user.
                    if ($overallstatus) {
                        if (debugging()) {
                            mtrace('Marking complete');
                        }

                        $ccompletion = new \completion_completion([
                            'course' => $params->course,
                            'userid' => $params->userid
                        ]);
                        $ccompletion->mark_complete($timecompleted);
                    }
                }

                // If this is the end of the recordset, break the loop.
                if (!$rs->valid()) {
                    $rs->close();
                    break;
                }

                // New/next user, update user details, reset completions.
                $currentuser = $record->userid;
                $currentcourse = $record->course;
                $completions = [];
                $completions[$record->criteriaid] = $record;
            }

            // Mark all users as aggregated.
            $sql = "UPDATE {course_completions}
                       SET reaggregate = 0
                     WHERE reaggregate < :timestarted
                       AND reaggregate > 0";
            $DB->execute($sql, ['timestarted' => $timestarted]);
        }
    }