3 namespace Friendica\Core;
5 use Friendica\BaseObject;
6 use Friendica\Database\DBA;
8 use Friendica\Model\Contact;
9 use Friendica\Model\GContact;
10 use Friendica\Network\HTTPException;
11 use Friendica\Network\Probe;
12 use Friendica\Object\Search\ContactResult;
13 use Friendica\Object\Search\ResultList;
14 use Friendica\Protocol\PortableContact;
15 use Friendica\Util\Network;
16 use Friendica\Util\Strings;
19 * Specific class to perform searches for different systems. Currently:
20 * - Probe for contacts
21 * - Search in the local directory
22 * - Search in the global directory
24 class Search extends BaseObject
26 const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
28 const TYPE_PEOPLE = 0;
33 * Search a user based on his/her profile address
34 * pattern: @username@domain.tld
36 * @param string $user The user to search for
39 * @throws HTTPException\InternalServerErrorException
40 * @throws \ImagickException
42 public static function getContactsFromProbe($user)
44 $emptyResultList = new ResultList(1, 0, 1);
46 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
47 (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
49 /// @todo Possibly use "getIdForURL" instead?
50 $user_data = Probe::uri($user);
51 if (empty($user_data)) {
52 return $emptyResultList;
55 if (!in_array($user_data["network"], Protocol::FEDERATED)) {
56 return $emptyResultList;
59 // Ensure that we do have a contact entry
60 Contact::getIdForURL($user_data['url'] ?? '');
62 $contactDetails = Contact::getDetailsByURL($user_data['url'] ?? '', local_user());
64 $result = new ContactResult(
65 $user_data['name'] ?? '',
66 $user_data['addr'] ?? '',
67 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
68 $user_data['url'] ?? '',
69 $user_data['photo'] ?? '',
70 $user_data['network'] ?? '',
71 $contactDetails['id'] ?? 0,
73 $user_data['tags'] ?? ''
76 return new ResultList(1, 1, 1, [$result]);
78 return $emptyResultList;
83 * Search in the global directory for occurrences of the search string
85 * @see https://github.com/friendica/friendica-directory/blob/master/docs/Protocol.md#search
87 * @param string $search
88 * @param int $type specific type of searching
92 * @throws HTTPException\InternalServerErrorException
94 public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
96 $config = DI::app()->getConfig();
97 $server = $config->get('system', 'directory', self::DEFAULT_DIRECTORY);
99 $searchUrl = $server . '/search';
102 case self::TYPE_FORUM:
103 $searchUrl .= '/forum';
105 case self::TYPE_PEOPLE:
106 $searchUrl .= '/people';
109 $searchUrl .= '?q=' . urlencode($search);
112 $searchUrl .= '&page=' . $page;
115 $resultJson = Network::fetchUrl($searchUrl, false, 0, 'application/json');
117 $results = json_decode($resultJson, true);
119 $resultList = new ResultList(
120 ($results['page'] ?? 0) ?: 1,
121 $results['count'] ?? 0,
122 ($results['itemsperpage'] ?? 0) ?: 30
125 $profiles = $results['profiles'] ?? [];
127 foreach ($profiles as $profile) {
128 $profile_url = $profile['profile_url'] ?? '';
129 $contactDetails = Contact::getDetailsByURL($profile_url, local_user());
131 $result = new ContactResult(
132 $profile['name'] ?? '',
133 $profile['addr'] ?? '',
134 ($contactDetails['addr'] ?? '') ?: $profile_url,
136 $profile['photo'] ?? '',
138 $contactDetails['cid'] ?? 0,
140 $profile['tags'] ?? ''
143 $resultList->addResult($result);
150 * Search in the local database for occurrences of the search string
152 * @param string $search
155 * @param int $itemPage
158 * @throws HTTPException\InternalServerErrorException
160 public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
162 $config = DI::app()->getConfig();
164 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
165 $ostatus = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
167 $wildcard = Strings::escapeHtml('%' . $search . '%');
169 $count = DBA::count('gcontact', [
171 AND `network` IN (?, ?, ?, ?)
172 AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
173 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
174 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
175 AND `community` = ?',
176 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
177 $wildcard, $wildcard, $wildcard,
178 $wildcard, $wildcard, $wildcard,
179 ($type === self::TYPE_FORUM),
182 $resultList = new ResultList($start, $itemPage, $count);
188 $data = DBA::select('gcontact', ['nurl'], [
190 AND `network` IN (?, ?, ?, ?)
191 AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
192 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
193 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
194 AND `community` = ?',
195 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
196 $wildcard, $wildcard, $wildcard,
197 $wildcard, $wildcard, $wildcard,
198 ($type === self::TYPE_FORUM),
200 'group_by' => ['nurl', 'updated'],
201 'limit' => [$start, $itemPage],
202 'order' => ['updated' => 'DESC']
205 if (!DBA::isResult($data)) {
209 while ($row = DBA::fetch($data)) {
210 if (PortableContact::alternateOStatusUrl($row["nurl"])) {
214 $urlParts = parse_url($row["nurl"]);
216 // Ignore results that look strange.
217 // For historic reasons the gcontact table does contain some garbage.
218 if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
222 $contact = Contact::getDetailsByURL($row["nurl"], local_user());
224 if ($contact["name"] == "") {
225 $contact["name"] = end(explode("/", $urlParts["path"]));
228 $result = new ContactResult(
240 $resultList->addResult($result);
245 // Add found profiles from the global directory to the local directory
246 Worker::add(PRIORITY_LOW, 'SearchDirectory', $search);
252 * Searching for global contacts for autocompletion
254 * @brief Searching for global contacts for autocompletion
255 * @param string $search Name or part of a name or nick
256 * @param string $mode Search mode (e.g. "community")
257 * @param int $page Page number (starts at 1)
258 * @return array with the search results
259 * @throws HTTPException\InternalServerErrorException
261 public static function searchGlobalContact($search, $mode, int $page = 1)
263 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
267 // don't search if search term has less than 2 characters
268 if (!$search || mb_strlen($search) < 2) {
272 if (substr($search, 0, 1) === '@') {
273 $search = substr($search, 1);
276 // check if searching in the local global contact table is enabled
277 if (Config::get('system', 'poco_local_search')) {
278 $return = GContact::searchByName($search, $mode);
280 $p = $page > 1 ? 'p=' . $page : '';
281 $curlResult = Network::curl(get_server() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
282 if ($curlResult->isSuccess()) {
283 $searchResult = json_decode($curlResult->getBody(), true);
284 if (!empty($searchResult['profiles'])) {
285 $return = $searchResult['profiles'];
290 return $return ?? [];