3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core;
25 use Friendica\Model\Contact;
26 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
27 use Friendica\Network\HTTPException;
28 use Friendica\Object\Search\ContactResult;
29 use Friendica\Object\Search\ResultList;
30 use Friendica\Util\Network;
31 use Friendica\Util\Strings;
32 use GuzzleHttp\Psr7\Uri;
35 * Specific class to perform searches for different systems. Currently:
36 * - Probe for contacts
37 * - Search in the local directory
38 * - Search in the global directory
42 const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
44 const TYPE_PEOPLE = 0;
49 * Search a user based on his/her profile address
50 * pattern: @username@domain.tld
52 * @param string $user The user to search for
55 * @throws HTTPException\InternalServerErrorException
56 * @throws \ImagickException
58 public static function getContactsFromProbe(string $user, $only_group = false): ResultList
60 $emptyResultList = new ResultList();
62 if (empty(parse_url($user, PHP_URL_SCHEME)) && !(filter_var($user, FILTER_VALIDATE_EMAIL) || Network::isEmailDomainValid($user))) {
63 return $emptyResultList;
66 $user_data = Contact::getByURL($user);
67 if (empty($user_data)) {
68 return $emptyResultList;
71 if ($only_group && ($user_data['contact-type'] != Contact::TYPE_COMMUNITY)) {
72 return $emptyResultList;
75 if (!Protocol::supportsProbe($user_data['network'])) {
76 return $emptyResultList;
79 $contactDetails = Contact::getByURLForUser($user_data['url'], DI::userSession()->getLocalUserId());
81 $result = new ContactResult(
84 $user_data['addr'] ?: $user_data['url'],
85 new Uri($user_data['url']),
87 $user_data['network'],
88 $contactDetails['cid'] ?? 0,
90 $user_data['keywords']
93 return new ResultList(1, 1, 1, [$result]);
97 * Search in the global directory for occurrences of the search string
99 * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
101 * @param string $search
102 * @param int $type specific type of searching
106 * @throws HTTPException\InternalServerErrorException
108 public static function getContactsFromGlobalDirectory(string $search, int $type = self::TYPE_ALL, int $page = 1): ResultList
110 $server = self::getGlobalDirectory();
112 $searchUrl = $server . '/search';
115 case self::TYPE_GROUP:
116 $searchUrl .= '/group';
118 case self::TYPE_PEOPLE:
119 $searchUrl .= '/people';
122 $searchUrl .= '?q=' . urlencode($search);
125 $searchUrl .= '&page=' . $page;
128 $resultJson = DI::httpClient()->fetch($searchUrl, HttpClientAccept::JSON);
130 $results = json_decode($resultJson, true);
132 $resultList = new ResultList(
133 ($results['page'] ?? 0) ?: 1,
134 $results['count'] ?? 0,
135 ($results['itemsperpage'] ?? 0) ?: 30
138 $profiles = $results['profiles'] ?? [];
140 foreach ($profiles as $profile) {
141 $profile_url = $profile['profile_url'] ?? '';
142 $contactDetails = Contact::getByURLForUser($profile_url, DI::userSession()->getLocalUserId());
144 $result = new ContactResult(
145 $profile['name'] ?? '',
146 $profile['addr'] ?? '',
147 ($contactDetails['addr'] ?? '') ?: $profile_url,
148 new Uri($profile_url),
149 $profile['photo'] ?? '',
151 $contactDetails['cid'] ?? 0,
152 $contactDetails['zid'] ?? 0,
153 $profile['tags'] ?? ''
156 $resultList->addResult($result);
163 * Search in the local database for occurrences of the search string
165 * @param string $search
168 * @param int $itemPage
171 * @throws HTTPException\InternalServerErrorException
173 public static function getContactsFromLocalDirectory(string $search, int $type = self::TYPE_ALL, int $start = 0, int $itemPage = 80): ResultList
175 Logger::info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]);
177 $contacts = Contact::searchByName($search, $type == self::TYPE_GROUP ? 'community' : '', true);
179 $resultList = new ResultList($start, count($contacts), $itemPage);
181 foreach ($contacts as $contact) {
182 $result = new ContactResult(
185 $contact['addr'] ?: $contact['url'],
186 new Uri($contact['url']),
194 $resultList->addResult($result);
197 // Add found profiles from the global directory to the local directory
198 Worker::add(Worker::PRIORITY_LOW, 'SearchDirectory', $search);
204 * Searching for contacts for autocompletion
206 * @param string $search Name or part of a name or nick
207 * @param string $mode Search mode (e.g. "community")
208 * @param int $page Page number (starts at 1)
210 * @return array with the search results or empty if error or nothing found
211 * @throws HTTPException\InternalServerErrorException
213 public static function searchContact(string $search, string $mode, int $page = 1): array
215 Logger::info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]);
217 if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
221 // don't search if search term has less than 2 characters
222 if (!$search || mb_strlen($search) < 2) {
226 if (substr($search, 0, 1) === '@') {
227 $search = substr($search, 1);
230 // check if searching in the local global contact table is enabled
231 if (DI::config()->get('system', 'poco_local_search')) {
232 $return = Contact::searchByName($search, $mode, true);
234 $p = $page > 1 ? 'p=' . $page : '';
235 $curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), HttpClientAccept::JSON);
236 if ($curlResult->isSuccess()) {
237 $searchResult = json_decode($curlResult->getBody(), true);
238 if (!empty($searchResult['profiles'])) {
239 // Converting Directory Search results into contact-looking records
240 $return = array_map(function ($result) {
241 static $contactType = [
242 'People' => Contact::TYPE_PERSON,
243 // Kept for backward compatibility
244 'Forum' => Contact::TYPE_COMMUNITY,
245 'Group' => Contact::TYPE_COMMUNITY,
246 'Organization' => Contact::TYPE_ORGANISATION,
247 'News' => Contact::TYPE_NEWS,
251 'name' => $result['name'],
252 'addr' => $result['addr'],
253 'url' => $result['profile_url'],
254 'network' => Protocol::DFRN,
255 'micro' => $result['photo'],
256 'contact-type' => $contactType[$result['account_type']],
258 }, $searchResult['profiles']);
263 return $return ?? [];
267 * Returns the global directory name, used in this node
271 public static function getGlobalDirectory(): string
273 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
277 * Return the search path (either fulltext search or tag search)
279 * @param string $search
281 * @return string search path
283 public static function getSearchPath(string $search): string
285 if (substr($search, 0, 1) == '#') {
286 return 'search?tag=' . urlencode(substr($search, 1));
288 return 'search?q=' . urlencode($search);