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 if (empty(parse_url($user, PHP_URL_SCHEME)) && !(filter_var($user, FILTER_VALIDATE_EMAIL) || Network::isEmailDomainValid($user))) {
64 $user_data = Contact::getByURL($user);
65 if (empty($user_data)) {
69 if (!Protocol::supportsProbe($user_data['network'])) {
73 $contactDetails = Contact::getByURLForUser($user_data['url'], DI::userSession()->getLocalUserId());
75 $result = new ContactResult(
78 $user_data['addr'] ?: $user_data['url'],
79 new Uri($user_data['url']),
81 $user_data['network'],
82 $contactDetails['cid'] ?? 0,
87 return new ResultList(1, 1, 1, [$result]);
91 * Search in the global directory for occurrences of the search string
93 * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
95 * @param string $search
96 * @param int $type specific type of searching
100 * @throws HTTPException\InternalServerErrorException
102 public static function getContactsFromGlobalDirectory(string $search, int $type = self::TYPE_ALL, int $page = 1): ResultList
104 $server = self::getGlobalDirectory();
106 $searchUrl = $server . '/search';
109 case self::TYPE_FORUM:
110 $searchUrl .= '/forum';
112 case self::TYPE_PEOPLE:
113 $searchUrl .= '/people';
116 $searchUrl .= '?q=' . urlencode($search);
119 $searchUrl .= '&page=' . $page;
122 $resultJson = DI::httpClient()->fetch($searchUrl, HttpClientAccept::JSON);
124 $results = json_decode($resultJson, true);
126 $resultList = new ResultList(
127 ($results['page'] ?? 0) ?: 1,
128 $results['count'] ?? 0,
129 ($results['itemsperpage'] ?? 0) ?: 30
132 $profiles = $results['profiles'] ?? [];
134 foreach ($profiles as $profile) {
135 $profile_url = $profile['profile_url'] ?? '';
136 $contactDetails = Contact::getByURLForUser($profile_url, DI::userSession()->getLocalUserId());
138 $result = new ContactResult(
139 $profile['name'] ?? '',
140 $profile['addr'] ?? '',
141 ($contactDetails['addr'] ?? '') ?: $profile_url,
142 new Uri($profile_url),
143 $profile['photo'] ?? '',
145 $contactDetails['cid'] ?? 0,
146 $contactDetails['zid'] ?? 0,
147 $profile['tags'] ?? ''
150 $resultList->addResult($result);
157 * Search in the local database for occurrences of the search string
159 * @param string $search
162 * @param int $itemPage
165 * @throws HTTPException\InternalServerErrorException
167 public static function getContactsFromLocalDirectory(string $search, int $type = self::TYPE_ALL, int $start = 0, int $itemPage = 80): ResultList
169 Logger::info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]);
171 $contacts = Contact::searchByName($search, $type == self::TYPE_FORUM ? 'community' : '', true);
173 $resultList = new ResultList($start, $itemPage, count($contacts));
175 foreach ($contacts as $contact) {
176 $result = new ContactResult(
179 $contact['addr'] ?: $contact['url'],
180 new Uri($contact['url']),
188 $resultList->addResult($result);
191 // Add found profiles from the global directory to the local directory
192 Worker::add(Worker::PRIORITY_LOW, 'SearchDirectory', $search);
198 * Searching for contacts for autocompletion
200 * @param string $search Name or part of a name or nick
201 * @param string $mode Search mode (e.g. "community")
202 * @param int $page Page number (starts at 1)
204 * @return array with the search results or empty if error or nothing found
205 * @throws HTTPException\InternalServerErrorException
207 public static function searchContact(string $search, string $mode, int $page = 1): array
209 Logger::info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]);
211 if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
215 // don't search if search term has less than 2 characters
216 if (!$search || mb_strlen($search) < 2) {
220 if (substr($search, 0, 1) === '@') {
221 $search = substr($search, 1);
224 // check if searching in the local global contact table is enabled
225 if (DI::config()->get('system', 'poco_local_search')) {
226 $return = Contact::searchByName($search, $mode, true);
228 $p = $page > 1 ? 'p=' . $page : '';
229 $curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), HttpClientAccept::JSON);
230 if ($curlResult->isSuccess()) {
231 $searchResult = json_decode($curlResult->getBody(), true);
232 if (!empty($searchResult['profiles'])) {
233 // Converting Directory Search results into contact-looking records
234 $return = array_map(function ($result) {
235 static $contactType = [
236 'People' => Contact::TYPE_PERSON,
237 'Forum' => Contact::TYPE_COMMUNITY,
238 'Organization' => Contact::TYPE_ORGANISATION,
239 'News' => Contact::TYPE_NEWS,
243 'name' => $result['name'],
244 'addr' => $result['addr'],
245 'url' => $result['profile_url'],
246 'network' => Protocol::DFRN,
247 'micro' => $result['photo'],
248 'contact-type' => $contactType[$result['account_type']],
250 }, $searchResult['profiles']);
255 return $return ?? [];
259 * Returns the global directory name, used in this node
263 public static function getGlobalDirectory(): string
265 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
269 * Return the search path (either fulltext search or tag search)
271 * @param string $search
273 * @return string search path
275 public static function getSearchPath(string $search): string
277 if (substr($search, 0, 1) == '#') {
278 return 'search?tag=' . urlencode(substr($search, 1));
280 return 'search?q=' . urlencode($search);