Searches for users given a query, taking into account the current user's permissions and
possibly a course to check within.

@param string $query Query text
@param int $courseid Course id or 0 if no restriction
@return array Defined return structure
510129
public static function get_relevant_users($query, $courseid) {
        global $CFG, $PAGE;

        // Validate parameter.
        self::validate_parameters(self::get_relevant_users_parameters(),
                ['query' => $query, 'courseid' => $courseid]);

        // Validate the context (search page is always system context).
        $systemcontext = \context_system::instance();
        self::validate_context($systemcontext);

        // Get course object too.
        if ($courseid) {
            $coursecontext = \context_course::instance($courseid);
        } else {
            $coursecontext = null;
        }

        // If not logged in, can't see anyone when forceloginforprofiles is on.
        if (!empty($CFG->forceloginforprofiles)) {
            if (!isloggedin() || isguestuser()) {
                return [];
            }
        }

        $users = \core_user::search($query, $coursecontext);

        $result = [];
        foreach ($users as $user) {
            // Get a standard exported user object.
            $fulldetails = (new user_summary_exporter($user))->export($PAGE->get_renderer('core'));

            // To avoid leaking private data to students, only include the specific information we
            // are going to display (and not the email, idnumber, etc).
            $result[] = (object)['id' => $fulldetails->id, 'fullname' => $fulldetails->fullname,
                    'profileimageurlsmall' => $fulldetails->profileimageurlsmall];
        }
        return $result;
    }
959631
public function makeQueryFiltered($query)
    {
        $settingTarget = $this->getSettingTarget();
        if ($settingTarget) {
            $query = $query->where([
                ['settable_id', '=', $settingTarget->getKeyName()],
                ['settable_type', '=', $settingTarget->getMorphClass()]
            ]);
        } else {
            $query = $query->whereNull('settable_id')->whereNull('settable_type');
        }
        return $query;
    }
1345508
public function findCurrent(Query $query, array $options)
    {
        $query
            ->where(['Current.language_id' => Wasabi::contentLanguage()->id])
            ->order(['Current.modified' => 'DESC'])->limit(1);
        return $query;
    }
567620
public function findWithGroupName(Query $query)
    {
        return $query
            ->select([
                'id',
                'username',
                'email',
                'verified',
                'active'
            ])
            ->contain([
                'Groups' => function (Query $q) {
                    return $q->select(['name']);
                }
            ]);
    }
80585
public function search($query, $limit = Pagination::DEFAULT_LIMIT)
    {
        return $this->paginateCustom(function () use ($query) {
            return $this->execSearchRequest($query, $this->getSearchScope());
        })->take($limit);
    }
810814
protected function searchProfiles( $query )
    {
        $token = $this->getOAuthToken();
        if (!$token) return;

        $response = Unirest\Request::get(
            "https://pub.orcid.org/v1.2/search/orcid-bio/",
            [
                'Authorization' => "Bearer $token",
                'Content-Type' => 'application/orcid+json'
            ],
            # TODO: search in names only and use boosting
            [ 'q' => luceneQuery('text',$query) ]
        );

        if ($response->code == 200) {
            return $response->body->{'orcid-search-results'};
        }
    }
664987
public function filter($query)
    {
        foreach ($this->getRules() as $name => $rule) {

            if ($this->getFormData($name) == '') {
                continue;
            }

            $type = $rule[0];

            switch ($type) {
                case 'primary':
                    $query->where($name, '=', $this->getFormData($name));
                    // Exit out of the loop, we don't need to process other conditions
                    break 2;

                case 'in':
                    $query->whereIn($rule[1], $this->getFormData($name));
                    break;

                case 'from':
                    $query->where($rule[1], '>=', date('Y-m-d 00:00:00', strtotime($this->getFormData($name))));
                    break;

                case 'to':
                    $query->where($rule[1], '<=', date('Y-m-d 23:59:59', strtotime($this->getFormData($name))));
                    break;

                case 'like':
                    $field = $name;
                    if (isset($rule[1])) {
                        $field = $rule[1];
                    }
                    $query->where($field, 'like', $this->getFormData($name) . '%');
                    break;

                case 'scope':
                    if ($this->getFormData($name)) {
                        $scope = $name;
                        $query->$scope();
                    }
                    break;

                default:
                    $field = $name;
                    if (isset($rule[1])) {
                        $field = $rule[1];
                    }
                    $query->where($field, '=', $this->getFormData($name));
                    break;
            }
        }

        return $query;
    }
354738
protected function getListQuery($query = null)
	{
		$db = JFactory::getDbo();

		// Check if we can use the supplied SQL query.
		$query = $query instanceof JDatabaseQuery ? $query : $db->getQuery(true)
			->select('a.id, a.title, a.alias, a.description AS summary, a.extension')
			->select('a.created_user_id AS created_by, a.modified_time AS modified, a.modified_user_id AS modified_by')
			->select('a.metakey, a.metadesc, a.metadata, a.language, a.lft, a.parent_id, a.level')
			->select('a.created_time AS start_date, a.published AS state, a.access, a.params');

		// Handle the alias CASE WHEN portion of the query.
		$case_when_item_alias = ' CASE WHEN ';
		$case_when_item_alias .= $query->charLength('a.alias', '!=', '0');
		$case_when_item_alias .= ' THEN ';
		$a_id = $query->castAsChar('a.id');
		$case_when_item_alias .= $query->concatenate(array($a_id, 'a.alias'), ':');
		$case_when_item_alias .= ' ELSE ';
		$case_when_item_alias .= $a_id . ' END as slug';
		$query->select($case_when_item_alias)
			->from('#__categories AS a')
			->where($db->quoteName('a.id') . ' > 1');

		return $query;
	}
231813
private function extractSearchTerms(string $query): array
    {
        $search_terms = [];

        // Words in double quotes stay together
        while (preg_match('/"([^"]+)"/', $query, $match)) {
            $search_terms[] = trim($match[1]);
            $query          = str_replace($match[0], '', $query);
        }

        // Other words get treated separately
        while (preg_match('/[\S]+/', $query, $match)) {
            $search_terms[] = trim($match[0]);
            $query          = str_replace($match[0], '', $query);
        }

        return $search_terms;
    }
592010
public function modify_query( $query ) {
		$is_users = 'pre_get_users' === current_filter();

		if ( $is_users ) {
			// This is not working until we fix the user query bit.
		} else {
			$types = $_POST['search_types'];
			$types = is_array( $types ) ? array_map( 'esc_attr', $types ) : esc_attr( $types );
			$query->set( 'post_type', $types );
		}

		if ( ! empty( $_POST['retrieved'] ) && is_array( $_POST['retrieved'] ) ) {
			// Exclude posts/users already existing.
			$ids = array_map( 'absint', $_POST['retrieved'] );

			if ( ! empty( $_POST['exclude'] ) && is_array( $_POST['exclude'] ) ) {
				// Exclude the post that we're looking at.
				$exclude = array_map( 'absint', $_POST['exclude'] );
				$ids = array_merge( $ids, $exclude );
			}

			$query->set( $is_users ? 'exclude' : 'post__not_in', $ids );
		}

		$this->maybe_callback( $query, $_POST );
	}
17746
public function search($query)
    {
        $searchProviders = [];

        foreach ($this->searchProviders as $searchProvider) {
            if (!$searchProvider instanceof SearchProviderInterface) {
                continue;
            }

            $role = $searchProvider->getRole();
            if ($role && !$this->authorizationChecker->isGranted($role)) {
                continue;
            }

            $searchProviders[] = $searchProvider;
        }

        $explodedQuery = explode(':', $query);
        if (count($explodedQuery) > 1) {
            $keySearchProviders = [];
            $keyWord = strtolower(array_shift($explodedQuery));

            foreach ($searchProviders as $searchProvider) {
                $searchKey = $searchProvider->getSearchKey();
                if ($searchKey === $keyWord) {
                    $keySearchProviders[] = $searchProvider;
                }
            }

            if (count($keySearchProviders)) {
                $searchProviders = $keySearchProviders;
                $query = trim(implode(':', $explodedQuery));
            }
        }

        $results = [];
        foreach ($searchProviders as $searchProvider) {
            $searchResults = $searchProvider->search($query);
            foreach ($searchResults as $searchResult) {
                $results[] = $searchResult->toArray();
            }
        }

        return $results;
    }
22221
public static function search_users($query, $capability = '', $limitfrom = 0, $limitnum = 100) {
        global $DB, $CFG, $PAGE, $USER;

        $params = self::validate_parameters(self::search_users_parameters(), array(
            'query' => $query,
            'capability' => $capability,
            'limitfrom' => $limitfrom,
            'limitnum' => $limitnum,
        ));
        $query = $params['query'];
        $cap = $params['capability'];
        $limitfrom = $params['limitfrom'];
        $limitnum = $params['limitnum'];

        $context = context_system::instance();
        self::validate_context($context);
        $output = $PAGE->get_renderer('tool_lp');

        list($filtercapsql, $filtercapparams) = api::filter_users_with_capability_on_user_context_sql($cap,
            $USER->id, SQL_PARAMS_NAMED);

        $extrasearchfields = array();
        if (!empty($CFG->showuseridentity) && has_capability('moodle/site:viewuseridentity', $context)) {
            $extrasearchfields = explode(',', $CFG->showuseridentity);
        }
        $fields = \user_picture::fields('u', $extrasearchfields);

        list($wheresql, $whereparams) = users_search_sql($query, 'u', true, $extrasearchfields);
        list($sortsql, $sortparams) = users_order_by_sql('u', $query, $context);

        $countsql = "SELECT COUNT('x') FROM {user} u WHERE $wheresql AND u.id $filtercapsql";
        $countparams = $whereparams + $filtercapparams;
        $sql = "SELECT $fields FROM {user} u WHERE $wheresql AND u.id $filtercapsql ORDER BY $sortsql";
        $params = $whereparams + $filtercapparams + $sortparams;

        $count = $DB->count_records_sql($countsql, $countparams);
        $result = $DB->get_recordset_sql($sql, $params, $limitfrom, $limitnum);

        $users = array();
        foreach ($result as $key => $user) {
            // Make sure all required fields are set.
            foreach (user_summary_exporter::define_properties() as $propertykey => $definition) {
                if (empty($user->$propertykey) || !in_array($propertykey, $extrasearchfields)) {
                    if ($propertykey != 'id') {
                        $user->$propertykey = '';
                    }
                }
            }
            $exporter = new user_summary_exporter($user);
            $newuser = $exporter->export($output);

            $users[$key] = $newuser;
        }
        $result->close();

        return array(
            'users' => $users,
            'count' => $count
        );
    }
1327527
public function find_users($search) {
        global $DB;

        $whereconditions = array();
        list($wherecondition, $params) = $this->search_sql($search, 'u');
        if ($wherecondition) {
            $whereconditions[] = $wherecondition;
        }

        if (!$this->forcesubscribed) {
            $existingids = array();
            foreach ($this->existingsubscribers as $group) {
                foreach ($group as $user) {
                    $existingids[$user->id] = 1;
                }
            }
            if ($existingids) {
                list($usertest, $userparams) = $DB->get_in_or_equal(
                        array_keys($existingids), SQL_PARAMS_NAMED, 'existing', false);
                $whereconditions[] = 'u.id ' . $usertest;
                $params = array_merge($params, $userparams);
            }
        }

        if ($whereconditions) {
            $wherecondition = 'WHERE ' . implode(' AND ', $whereconditions);
        }

        list($esql, $eparams) = get_enrolled_sql($this->context, '', $this->currentgroup, true);
        $params = array_merge($params, $eparams);

        $fields      = 'SELECT ' . $this->required_fields_sql('u');

        $sql = " FROM {user} u
                 JOIN ($esql) je ON je.id = u.id
                      $wherecondition";

        list($sort, $sortparams) = users_order_by_sql('u', $search, $this->accesscontext);
        $order = ' ORDER BY ' . $sort;

        $availableusers = $DB->get_records_sql($fields . $sql . $order, array_merge($params, $sortparams));

        $cm = get_coursemodule_from_instance('forum', $this->forumid);
        $modinfo = get_fast_modinfo($cm->course);
        $info = new \core_availability\info_module($modinfo->get_cm($cm->id));
        $availableusers = $info->filter_user_list($availableusers);

        if (empty($availableusers)) {
            return array();
        }

        // Check to see if there are too many to show sensibly.
        if (!$this->is_validating()) {
            $potentialmemberscount = count($availableusers);
            if ($potentialmemberscount > $this->maxusersperpage) {
                return $this->too_many_results($search, $potentialmemberscount);
            }
        }

        if ($this->forcesubscribed) {
            return array(get_string("existingsubscribers", 'forum') => $availableusers);
        } else {
            return array(get_string("potentialsubscribers", 'forum') => $availableusers);
        }
    }
1177983
public function scopeMembers(Builder $query)
    {
        $query->with('roles')->whereNotNull('tbl_users.id')->whereHas('roles', function ($query) {
            $query->whereIn('tbl_roles.name', ['member', 'client']);
        });


        return $query;
    }
1372688
public function query( $query ) {
		if ( ! $this->ready ) {
			if ( isset( $this->check_current_query ) ) {
				// This property was introduced in WP 4.2
				$this->check_current_query = true;
			}
			return false;
		}

		if ( $this->show_errors ) {
			$this->hide_errors();
		}

		$result = parent::query( $query );

		if ( ! SAVEQUERIES ) {
			return $result;
		}

		$i = $this->num_queries - 1;
		$this->queries[ $i ]['trace'] = new QM_Backtrace( array(
			'ignore_frames' => 1,
		) );

		if ( ! isset( $this->queries[ $i ][3] ) ) {
			$this->queries[ $i ][3] = $this->time_start;
		}

		if ( $this->last_error ) {
			$code = 'qmdb';
			if ( $this->use_mysqli ) {
				if ( $this->dbh instanceof mysqli ) {
					$code = mysqli_errno( $this->dbh );
				}
			} else {
				if ( is_resource( $this->dbh ) ) {
					// Please do not report this code as a PHP 7 incompatibility. Observe the surrounding logic.
					// @codingStandardsIgnoreLine
					$code = mysql_errno( $this->dbh );
				}
			}
			$this->queries[ $i ]['result'] = new WP_Error( $code, $this->last_error );
		} else {
			$this->queries[ $i ]['result'] = $result;
		}

		return $result;
	}
1086975
public function constrainWhereIsAll($query, $role)
    {
        $roles = array_slice(func_get_args(), 1);

        return $query->whereHas('roles', function ($query) use ($roles) {
            $query->whereIn('name', $roles);
        }, '=', count($roles));
    }
29570
public function queryFromFilter(Query $query, array $data = [])
    {
        $query = parent::queryFromFilter($query, $data);

        //"Username" field
        if (!empty($data['username']) && strlen($data['username']) > 2) {
            $query->where([sprintf('%s.username LIKE', $this->getAlias()) => sprintf('%%%s%%', $data['username'])]);
        }

        //"Group" field
        if (!empty($data['group']) && is_positive($data['group'])) {
            $query->where([sprintf('%s.group_id', $this->getAlias()) => $data['group']]);
        }

        //"Status" field
        if (!empty($data['status'])) {
            switch ($data['status']) {
                case 'active':
                    $query->where([
                        sprintf('%s.active', $this->getAlias()) => true,
                        sprintf('%s.banned', $this->getAlias()) => false,
                    ]);

                    break;
                case 'pending':
                    $query->where([sprintf('%s.active', $this->getAlias()) => false]);

                    break;
                case 'banned':
                    $query->where([sprintf('%s.banned', $this->getAlias()) => true]);

                    break;
            }
        }

        return $query;
    }