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): ResultList
60 $emptyResultList = new ResultList(1, 0, 1);
62 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
63 (substr(Strings::normaliseLink($user), 0, 7) == 'http://')) {
65 $user_data = Contact::getByURL($user);
66 if (empty($user_data)) {
67 return $emptyResultList;
70 if (!in_array($user_data['network'], Protocol::FEDERATED)) {
71 return $emptyResultList;
74 $contactDetails = Contact::getByURLForUser($user_data['url'] ?? '', DI::userSession()->getLocalUserId());
76 $result = new ContactResult(
77 $user_data['name'] ?? '',
78 $user_data['addr'] ?? '',
79 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
80 new Uri($user_data['url'] ?? ''),
81 $user_data['photo'] ?? '',
82 $user_data['network'] ?? '',
83 $contactDetails['cid'] ?? 0,
84 $user_data['id'] ?? 0,
85 $user_data['tags'] ?? ''
88 return new ResultList(1, 1, 1, [$result]);
90 return $emptyResultList;
95 * Search in the global directory for occurrences of the search string
97 * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
99 * @param string $search
100 * @param int $type specific type of searching
104 * @throws HTTPException\InternalServerErrorException
106 public static function getContactsFromGlobalDirectory(string $search, int $type = self::TYPE_ALL, int $page = 1): ResultList
108 $server = self::getGlobalDirectory();
110 $searchUrl = $server . '/search';
113 case self::TYPE_FORUM:
114 $searchUrl .= '/forum';
116 case self::TYPE_PEOPLE:
117 $searchUrl .= '/people';
120 $searchUrl .= '?q=' . urlencode($search);
123 $searchUrl .= '&page=' . $page;
126 $resultJson = DI::httpClient()->fetch($searchUrl, HttpClientAccept::JSON);
128 $results = json_decode($resultJson, true);
130 $resultList = new ResultList(
131 ($results['page'] ?? 0) ?: 1,
132 $results['count'] ?? 0,
133 ($results['itemsperpage'] ?? 0) ?: 30
136 $profiles = $results['profiles'] ?? [];
138 foreach ($profiles as $profile) {
139 $profile_url = $profile['profile_url'] ?? '';
140 $contactDetails = Contact::getByURLForUser($profile_url, DI::userSession()->getLocalUserId());
142 $result = new ContactResult(
143 $profile['name'] ?? '',
144 $profile['addr'] ?? '',
145 ($contactDetails['addr'] ?? '') ?: $profile_url,
146 new Uri($profile_url),
147 $profile['photo'] ?? '',
149 $contactDetails['cid'] ?? 0,
150 $contactDetails['zid'] ?? 0,
151 $profile['tags'] ?? ''
154 $resultList->addResult($result);
161 * Search in the local database for occurrences of the search string
163 * @param string $search
166 * @param int $itemPage
169 * @throws HTTPException\InternalServerErrorException
171 public static function getContactsFromLocalDirectory(string $search, int $type = self::TYPE_ALL, int $start = 0, int $itemPage = 80): ResultList
173 Logger::info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]);
175 $contacts = Contact::searchByName($search, $type == self::TYPE_FORUM ? 'community' : '', true);
177 $resultList = new ResultList($start, $itemPage, count($contacts));
179 foreach ($contacts as $contact) {
180 $result = new ContactResult(
183 $contact['addr'] ?: $contact['url'],
184 new Uri($contact['url']),
192 $resultList->addResult($result);
195 // Add found profiles from the global directory to the local directory
196 Worker::add(Worker::PRIORITY_LOW, 'SearchDirectory', $search);
202 * Searching for contacts for autocompletion
204 * @param string $search Name or part of a name or nick
205 * @param string $mode Search mode (e.g. "community")
206 * @param int $page Page number (starts at 1)
208 * @return array with the search results or empty if error or nothing found
209 * @throws HTTPException\InternalServerErrorException
211 public static function searchContact(string $search, string $mode, int $page = 1): array
213 Logger::info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]);
215 if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
219 // don't search if search term has less than 2 characters
220 if (!$search || mb_strlen($search) < 2) {
224 if (substr($search, 0, 1) === '@') {
225 $search = substr($search, 1);
228 // check if searching in the local global contact table is enabled
229 if (DI::config()->get('system', 'poco_local_search')) {
230 $return = Contact::searchByName($search, $mode, true);
232 $p = $page > 1 ? 'p=' . $page : '';
233 $curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), HttpClientAccept::JSON);
234 if ($curlResult->isSuccess()) {
235 $searchResult = json_decode($curlResult->getBody(), true);
236 if (!empty($searchResult['profiles'])) {
237 // Converting Directory Search results into contact-looking records
238 $return = array_map(function ($result) {
239 static $contactType = [
240 'People' => Contact::TYPE_PERSON,
241 'Forum' => Contact::TYPE_COMMUNITY,
242 'Organization' => Contact::TYPE_ORGANISATION,
243 'News' => Contact::TYPE_NEWS,
247 'name' => $result['name'],
248 'addr' => $result['addr'],
249 'url' => $result['profile_url'],
250 'network' => Protocol::DFRN,
251 'micro' => $result['photo'],
252 'contact-type' => $contactType[$result['account_type']],
254 }, $searchResult['profiles']);
259 return $return ?? [];
263 * Returns the global directory name, used in this node
267 public static function getGlobalDirectory(): string
269 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
273 * Return the search path (either fulltext search or tag search)
275 * @param string $search
277 * @return string search path
279 public static function getSearchPath(string $search): string
281 if (substr($search, 0, 1) == '#') {
282 return 'search?tag=' . urlencode(substr($search, 1));
284 return 'search?q=' . urlencode($search);