Handles searching for user.

@param int $userid The user id doing the searching
@param string $search The string the user is searching
@param int $limitfrom
@param int $limitnum
@return array
173686
public static function message_search_users(int $userid, string $search, int $limitfrom = 0, int $limitnum = 20) : array {
        global $CFG, $DB;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new \moodle_exception('disabled', 'message');
        }

        // Used to search for contacts.
        $fullname = $DB->sql_fullname();

        // Users not to include.
        $excludeusers = array($CFG->siteguest);
        if (!$selfconversation = self::get_self_conversation($userid)) {
            // Userid should only be excluded when she hasn't a self-conversation.
            $excludeusers[] = $userid;
        }
        list($exclude, $excludeparams) = $DB->get_in_or_equal($excludeusers, SQL_PARAMS_NAMED, 'param', false);

        $params = array('search' => '%' . $DB->sql_like_escape($search) . '%', 'userid1' => $userid, 'userid2' => $userid);

        // Ok, let's search for contacts first.
        $sql = "SELECT u.id
                  FROM {user} u
                  JOIN {message_contacts} mc
                    ON (u.id = mc.contactid AND mc.userid = :userid1) OR (u.id = mc.userid AND mc.contactid = :userid2)
                 WHERE u.deleted = 0
                   AND u.confirmed = 1
                   AND " . $DB->sql_like($fullname, ':search', false) . "
                   AND u.id $exclude
              ORDER BY " . $DB->sql_fullname();
        $foundusers = $DB->get_records_sql_menu($sql, $params + $excludeparams, $limitfrom, $limitnum);

        $contacts = [];
        if (!empty($foundusers)) {
            $contacts = helper::get_member_info($userid, array_keys($foundusers));
            foreach ($contacts as $memberuserid => $memberinfo) {
                $contacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0, 1000);
            }
        }

        // Let's get those non-contacts.
        // Because we can't achieve all the required visibility checks in SQL, we'll iterate through the non-contact records
        // and stop once we have enough matching the 'visible' criteria.
        // TODO: MDL-63983 - Improve the performance of non-contact searches when site-wide messaging is disabled (default).

        // Use a local generator to achieve this iteration.
        $getnoncontactusers = function ($limitfrom = 0, $limitnum = 0) use($fullname, $exclude, $params, $excludeparams) {
            global $DB;
            $sql = "SELECT u.*
                  FROM {user} u
                 WHERE u.deleted = 0
                   AND u.confirmed = 1
                   AND " . $DB->sql_like($fullname, ':search', false) . "
                   AND u.id $exclude
                   AND NOT EXISTS (SELECT mc.id
                                     FROM {message_contacts} mc
                                    WHERE (mc.userid = u.id AND mc.contactid = :userid1)
                                       OR (mc.userid = :userid2 AND mc.contactid = u.id))
              ORDER BY " . $DB->sql_fullname();
            while ($records = $DB->get_records_sql($sql, $params + $excludeparams, $limitfrom, $limitnum)) {
                yield $records;
                $limitfrom += $limitnum;
            }
        };

        // Fetch in batches of $limitnum * 2 to improve the chances of matching a user without going back to the DB.
        // The generator cannot function without a sensible limiter, so set one if this is not set.
        $batchlimit = ($limitnum == 0) ? 20 : $limitnum;

        // We need to make the offset param work with the generator.
        // Basically, if we want to get say 10 records starting at the 40th record, we need to see 50 records and return only
        // those after the 40th record. We can never pass the method's offset param to the generator as we need to manage the
        // position within those valid records ourselves.
        // See MDL-63983 dealing with performance improvements to this area of code.
        $noofvalidseenrecords = 0;
        $returnedusers = [];
        foreach ($getnoncontactusers(0, $batchlimit) as $users) {
            foreach ($users as $id => $user) {
                // User visibility checks: only return users who are visible to the user performing the search.
                // Which visibility check to use depends on the 'messagingallusers' (site wide messaging) setting:
                // - If enabled, return matched users whose profiles are visible to the current user anywhere (site or course).
                // - If disabled, only return matched users whose course profiles are visible to the current user.
                $userdetails = \core_message\helper::search_get_user_details($user);

                // Return the user only if the searched field is returned.
                // Otherwise it means that the $USER was not allowed to search the returned user.
                if (!empty($userdetails) and !empty($userdetails['fullname'])) {
                    // We know we've matched, but only save the record if it's within the offset area we need.
                    if ($limitfrom == 0) {
                        // No offset specified, so just save.
                        $returnedusers[$id] = $user;
                    } else {
                        // There is an offset in play.
                        // If we've passed enough records already (> offset value), then we can save this one.
                        if ($noofvalidseenrecords >= $limitfrom) {
                            $returnedusers[$id] = $user;
                        }
                    }
                    if (count($returnedusers) == $limitnum) {
                        break 2;
                    }
                    $noofvalidseenrecords++;
                }
            }
        }
        $foundusers = $returnedusers;

        $noncontacts = [];
        if (!empty($foundusers)) {
            $noncontacts = helper::get_member_info($userid, array_keys($foundusers));
            foreach ($noncontacts as $memberuserid => $memberinfo) {
                if ($memberuserid !== $userid) {
                    $noncontacts[$memberuserid]->conversations = self::get_conversations_between_users($userid, $memberuserid, 0,
                        1000);
                } else {
                    $noncontacts[$memberuserid]->conversations[$selfconversation->id] = $selfconversation;
                }
            }
        }

        return array(array_values($contacts), array_values($noncontacts));
    }
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);
        }
    }
787641
public function find_users($search) {
        global $DB;
        list($wherecondition, $params) = $this->search_sql($search, 'u');
        $params['forumid'] = $this->forumid;

        // only active enrolled or everybody on the frontpage
        list($esql, $eparams) = get_enrolled_sql($this->context, '', $this->currentgroup, true);
        $fields = $this->required_fields_sql('u');
        list($sort, $sortparams) = users_order_by_sql('u', $search, $this->accesscontext);
        $params = array_merge($params, $eparams, $sortparams);

        $subscribers = $DB->get_records_sql("SELECT $fields
                                               FROM {user} u
                                               JOIN ($esql) je ON je.id = u.id
                                               JOIN {forum_subscriptions} s ON s.userid = u.id
                                              WHERE $wherecondition AND s.forum = :forumid
                                           ORDER BY $sort", $params);

        $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));
        $subscribers = $info->filter_user_list($subscribers);

        return array(get_string("existingsubscribers", 'forum') => $subscribers);
    }
80585
public function search($query, $limit = Pagination::DEFAULT_LIMIT)
    {
        return $this->paginateCustom(function () use ($query) {
            return $this->execSearchRequest($query, $this->getSearchScope());
        })->take($limit);
    }
986016
public static function data_for_messagearea_search_messages($userid, $search, $limitfrom = 0, $limitnum = 0) {
        global $CFG, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        $systemcontext = context_system::instance();

        $params = array(
            'userid' => $userid,
            'search' => $search,
            'limitfrom' => $limitfrom,
            'limitnum' => $limitnum

        );
        $params = self::validate_parameters(self::data_for_messagearea_search_messages_parameters(), $params);
        self::validate_context($systemcontext);

        if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
            throw new moodle_exception('You do not have permission to perform this action.');
        }

        $messages = \core_message\api::search_messages(
            $params['userid'],
            $params['search'],
            $params['limitfrom'],
            $params['limitnum']
        );

        $data = new \stdClass();
        $data->contacts = [];
        foreach ($messages as $message) {
            $contact = new \stdClass();
            $contact->userid = $message->userid;
            $contact->fullname = $message->fullname;
            $contact->profileimageurl = $message->profileimageurl;
            $contact->profileimageurlsmall = $message->profileimageurlsmall;
            $contact->messageid = $message->messageid;
            $contact->ismessaging = $message->ismessaging;
            $contact->sentfromcurrentuser = false;
            if ($message->lastmessage) {
                if ($message->userid !== $message->useridfrom) {
                    $contact->sentfromcurrentuser = true;
                }
                $contact->lastmessage = shorten_text($message->lastmessage, 60);
            } else {
                $contact->lastmessage = null;
            }
            $contact->lastmessagedate = $message->lastmessagedate;
            $contact->showonlinestatus = is_null($message->isonline) ? false : true;
            $contact->isonline = $message->isonline;
            $contact->isblocked = $message->isblocked;
            $contact->isread = $message->isread;
            $contact->unreadcount = $message->unreadcount;
            $contact->conversationid = $message->conversationid;

            $data->contacts[] = $contact;
        }

        return $data;
    }
847815
static function fetchListForUser( $userID, $offset = false, $limit = false )
    {
        $objectList = eZPersistentObject::fetchObjectList( eZContentBrowseBookmark::definition(),
                                                            null,
                                                            array( 'user_id' => $userID ),
                                                            array( 'id' => 'desc' ),
                                                            array( 'offset' => $offset, 'length' => $limit ),
                                                            true );
        return $objectList;
    }
275909
public function TagSearch($Search) {
      $Search = trim(str_replace(array('%', '_'), array('\%', '\_'), $Search));
      
      $Results = $this->SQL
         ->Select('UserID', '', 'id')
         ->Select('Name', '', 'name')
         ->From('User')
         ->Like('Name', $Search, 'right')
         ->Where('Deleted', 0)
         ->Limit(10)
         ->Get()->ResultArray();
      return $Results;
   }
694361
public static function get_user_contacts(int $userid, int $limitfrom = 0, int $limitnum = 0) {
        global $CFG, $USER;

        // Check if messaging is enabled.
        if (empty($CFG->messaging)) {
            throw new moodle_exception('disabled', 'message');
        }

        $systemcontext = context_system::instance();

        $params = array(
            'userid' => $userid,
            'limitfrom' => $limitfrom,
            'limitnum' => $limitnum
        );
        $params = self::validate_parameters(self::get_user_contacts_parameters(), $params);
        self::validate_context($systemcontext);

        if (($USER->id != $params['userid']) && !has_capability('moodle/site:readallmessages', $systemcontext)) {
            throw new moodle_exception('You do not have permission to perform this action.');
        }

        return \core_message\api::get_user_contacts($params['userid'], $params['limitfrom'], $params['limitnum']);
    }
349247
public function find_users($search) {
        global $DB;
        list($wherecondition, $params) = $this->search_sql($search, 'u');
        $params['badgeid'] = $this->badgeid;
        $params['issuerrole'] = $this->issuerrole;

        list($esql, $eparams) = get_enrolled_sql($this->context, 'moodle/badges:earnbadge', 0, true);
        $fields = $this->required_fields_sql('u');
        list($sort, $sortparams) = users_order_by_sql('u', $search, $this->accesscontext);

        $params = array_merge($params, $eparams, $sortparams);
        $recipients = $DB->get_records_sql("SELECT $fields
                FROM {user} u
                JOIN ($esql) je ON je.id = u.id
                JOIN {badge_manual_award} s ON s.recipientid = u.id
                WHERE $wherecondition AND s.badgeid = :badgeid AND s.issuerrole = :issuerrole
                ORDER BY $sort", $params);

        return array(get_string('existingrecipients', 'badges') => $recipients);
    }
299414
public function searchIncidents($search, $by, $limit = 1, $num = 1000, $page = 1)
    {
        $incidents = $this->indexIncidents($num, $page)['data'];

        $filtered = array_filter(
            $incidents,
            function ($incident) use ($search, $by) {

                if (array_key_exists($by, $incident)) {
                    if (strpos($incident[$by], $search) !== false) {
                        return $incident;
                    }
                    if ($incident[$by] === $search) {
                        return $incident;
                    }
                }

                return false;
            }
        );

        if ($limit == 1) {
            return array_shift($filtered);
        }

        return array_slice($filtered, 0, $limit);
    }
152512
public function findOneByUserId($userId)
    {
        $qb = $this->createQueryBuilder();
        $qb->field('userId')->equals($userId);

        return $qb->getQuery()->getSingleResult();
    }
589878
public function likes($username, $limit = Pagination::DEFAULT_LIMIT)
    {
        return $this->paginateByUsername(
            $username, UrlBuilder::RESOURCE_USER_LIKES, $limit
        );
    }
684101
public static function get_non_contacts_with_unread_message_count($userid, $limitfrom = 0, $limitnum = 0) {
        global $DB;

        $userfields = \user_picture::fields('u', array('lastaccess'));
        $unreadcountssql = "SELECT $userfields, count(m.id) as messagecount
                              FROM {user} u
                        INNER JOIN {messages} m
                                ON m.useridfrom = u.id
                        INNER JOIN {message_conversation_members} mcm
                                ON mcm.conversationid = m.conversationid
                         LEFT JOIN {message_user_actions} mua
                                ON (mua.messageid = m.id AND mua.userid = ? AND mua.action = ?)
                         LEFT JOIN {message_contacts} mc
                                ON (mc.userid = ? AND mc.contactid = u.id)
                         LEFT JOIN {message_users_blocked} mub
                                ON (mub.userid = ? AND mub.blockeduserid = u.id)
                             WHERE mcm.userid = ?
                               AND mcm.userid != m.useridfrom
                               AND mua.id is NULL
                               AND mub.id is NULL
                               AND mc.id is NULL
                               AND u.deleted = 0
                          GROUP BY $userfields";

        return $DB->get_records_sql($unreadcountssql, [$userid, self::MESSAGE_ACTION_READ, $userid, $userid, $userid],
            $limitfrom, $limitnum);
    }
501044
public function findByUsernameContains($searched_term)
    {
        $qb = $this->createQueryBuilder('u');
        $qb instanceof QueryBuilder;

        $qb->add('where', $qb->expr()->like('u.username', $qb->expr()->lower(':searched_term')))
            ->setParameter('searched_term', $searched_term . '%');

        return $qb->getQuery()->getResult();
    }
295642
private static function search($query, $limit = 10)
	{
		$ch = curl_init(
			"https://brainly.co.id/api/28/api_tasks/suggester?limit=".((int) $limit)."&query=".urlencode($query)
		);
		curl_setopt_array(
			$ch, 
			[
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_SSL_VERIFYPEER => false,
				CURLOPT_SSL_VERIFYHOST => false,
				CURLOPT_CONNECTTIMEOUT => 15,
				CURLOPT_TIMEOUT => 15
			]
		);
		$out = curl_exec($ch);
		if (
			$no  = curl_errno($ch) and 
			$out = "Error ({$no}) : ".$out
		) {
			throw new \Exception($out, 1);
		}
		return $out;
	}
1067401
public function scopeSearch(Builder $query, $name, $userId)
    {
        return $query->where('user_id', '=', $userId)->where('name', '=', $name);
    }
216990
public function findLimited($limit = 0)
    {
        $queryBuilder = $this->createQueryBuilder('c')
            ->where('c.enabled = :enabled')
            ->orderBy('c.position')
            ->setParameters(array(
                'enabled' => true,
            ));

        if ($limit != 0) {
            $queryBuilder->setMaxResults($limit);
        }

        return $queryBuilder->getQuery()->getResult();
    }