3 * @copyright Copyright (C) 2020, Friendica
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;
24 use Friendica\Database\DBA;
26 use Friendica\Model\Contact;
27 use Friendica\Model\GContact;
28 use Friendica\Network\HTTPException;
29 use Friendica\Network\HTTPRequest;
30 use Friendica\Object\Search\ContactResult;
31 use Friendica\Object\Search\ResultList;
32 use Friendica\Util\Network;
33 use Friendica\Util\Strings;
36 * Specific class to perform searches for different systems. Currently:
37 * - Probe for contacts
38 * - Search in the local directory
39 * - Search in the global directory
43 const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
45 const TYPE_PEOPLE = 0;
50 * Search a user based on his/her profile address
51 * pattern: @username@domain.tld
53 * @param string $user The user to search for
56 * @throws HTTPException\InternalServerErrorException
57 * @throws \ImagickException
59 public static function getContactsFromProbe($user)
61 $emptyResultList = new ResultList(1, 0, 1);
63 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
64 (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
66 $user_data = Contact::getByURL($user);
67 if (empty($user_data)) {
68 return $emptyResultList;
71 if (!in_array($user_data["network"], Protocol::FEDERATED)) {
72 return $emptyResultList;
75 $contactDetails = Contact::getByURLForUser($user_data['url'] ?? '', local_user());
77 $result = new ContactResult(
78 $user_data['name'] ?? '',
79 $user_data['addr'] ?? '',
80 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
81 $user_data['url'] ?? '',
82 $user_data['photo'] ?? '',
83 $user_data['network'] ?? '',
84 $contactDetails['id'] ?? 0,
85 $user_data['id'] ?? 0,
86 $user_data['tags'] ?? ''
89 return new ResultList(1, 1, 1, [$result]);
91 return $emptyResultList;
96 * Search in the global directory for occurrences of the search string
98 * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
100 * @param string $search
101 * @param int $type specific type of searching
105 * @throws HTTPException\InternalServerErrorException
107 public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
109 $server = DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
111 $searchUrl = $server . '/search';
114 case self::TYPE_FORUM:
115 $searchUrl .= '/forum';
117 case self::TYPE_PEOPLE:
118 $searchUrl .= '/people';
121 $searchUrl .= '?q=' . urlencode($search);
124 $searchUrl .= '&page=' . $page;
127 $resultJson = HTTPRequest::fetchUrl($searchUrl, false, 0, 'application/json');
129 $results = json_decode($resultJson, true);
131 $resultList = new ResultList(
132 ($results['page'] ?? 0) ?: 1,
133 $results['count'] ?? 0,
134 ($results['itemsperpage'] ?? 0) ?: 30
137 $profiles = $results['profiles'] ?? [];
139 foreach ($profiles as $profile) {
140 $profile_url = $profile['url'] ?? '';
141 $contactDetails = Contact::getByURLForUser($profile_url, local_user());
143 $result = new ContactResult(
144 $profile['name'] ?? '',
145 $profile['addr'] ?? '',
146 ($contactDetails['addr'] ?? '') ?: $profile_url,
148 $profile['photo'] ?? '',
150 $contactDetails['cid'] ?? 0,
152 $profile['tags'] ?? ''
155 $resultList->addResult($result);
162 * Search in the local database for occurrences of the search string
164 * @param string $search
167 * @param int $itemPage
170 * @throws HTTPException\InternalServerErrorException
172 public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
174 $config = DI::config();
176 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
177 $ostatus = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
179 $wildcard = Strings::escapeHtml('%' . $search . '%');
181 $count = DBA::count('gcontact', [
183 AND `network` IN (?, ?, ?, ?)
185 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
186 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
187 AND `community` = ?',
188 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
189 $wildcard, $wildcard, $wildcard,
190 $wildcard, $wildcard, $wildcard,
191 ($type === self::TYPE_FORUM),
194 $resultList = new ResultList($start, $itemPage, $count);
200 $data = DBA::select('gcontact', ['nurl', 'name', 'addr', 'url', 'photo', 'network', 'keywords'], [
202 AND `network` IN (?, ?, ?, ?)
204 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
205 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
206 AND `community` = ?',
207 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
208 $wildcard, $wildcard, $wildcard,
209 $wildcard, $wildcard, $wildcard,
210 ($type === self::TYPE_FORUM),
212 'group_by' => ['nurl', 'updated'],
213 'limit' => [$start, $itemPage],
214 'order' => ['updated' => 'DESC']
217 if (!DBA::isResult($data)) {
221 while ($row = DBA::fetch($data)) {
222 $urlParts = parse_url($row["nurl"]);
224 // Ignore results that look strange.
225 // For historic reasons the gcontact table does contain some garbage.
226 if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
230 $contact = Contact::getByURLForUser($row["nurl"], local_user()) ?: $row;
232 if ($contact["name"] == "") {
233 $contact["name"] = end(explode("/", $urlParts["path"]));
236 $result = new ContactResult(
243 $contact["cid"] ?? 0,
244 $contact["zid"] ?? 0,
248 $resultList->addResult($result);
253 // Add found profiles from the global directory to the local directory
254 Worker::add(PRIORITY_LOW, 'SearchDirectory', $search);
260 * Searching for global contacts for autocompletion
262 * @param string $search Name or part of a name or nick
263 * @param string $mode Search mode (e.g. "community")
264 * @param int $page Page number (starts at 1)
265 * @return array with the search results
266 * @throws HTTPException\InternalServerErrorException
268 public static function searchGlobalContact($search, $mode, int $page = 1)
270 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
274 // don't search if search term has less than 2 characters
275 if (!$search || mb_strlen($search) < 2) {
279 if (substr($search, 0, 1) === '@') {
280 $search = substr($search, 1);
283 // check if searching in the local global contact table is enabled
284 if (DI::config()->get('system', 'poco_local_search')) {
285 $return = GContact::searchByName($search, $mode);
287 $p = $page > 1 ? 'p=' . $page : '';
288 $curlResult = HTTPRequest::curl(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
289 if ($curlResult->isSuccess()) {
290 $searchResult = json_decode($curlResult->getBody(), true);
291 if (!empty($searchResult['profiles'])) {
292 $return = $searchResult['profiles'];
297 return $return ?? [];
301 * Returns the global directory name, used in this node
305 public static function getGlobalDirectory()
307 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
311 * Return the search path (either fulltext search or tag search)
313 * @param string $search
314 * @return string search path
316 public static function getSearchPath(string $search)
318 if (substr($search, 0, 1) == '#') {
319 return 'search?tag=' . urlencode(substr($search, 1));
321 return 'search?q=' . urlencode($search);