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\Probe;
30 use Friendica\Object\Search\ContactResult;
31 use Friendica\Object\Search\ResultList;
32 use Friendica\Protocol\PortableContact;
33 use Friendica\Util\Network;
34 use Friendica\Util\Strings;
37 * Specific class to perform searches for different systems. Currently:
38 * - Probe for contacts
39 * - Search in the local directory
40 * - Search in the global directory
44 const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
46 const TYPE_PEOPLE = 0;
51 * Search a user based on his/her profile address
52 * pattern: @username@domain.tld
54 * @param string $user The user to search for
57 * @throws HTTPException\InternalServerErrorException
58 * @throws \ImagickException
60 public static function getContactsFromProbe($user)
62 $emptyResultList = new ResultList(1, 0, 1);
64 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
65 (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
67 /// @todo Possibly use "getIdForURL" instead?
68 $user_data = Probe::uri($user);
69 if (empty($user_data)) {
70 return $emptyResultList;
73 if (!in_array($user_data["network"], Protocol::FEDERATED)) {
74 return $emptyResultList;
77 // Ensure that we do have a contact entry
78 Contact::getIdForURL($user_data['url'] ?? '');
80 $contactDetails = Contact::getDetailsByURL($user_data['url'] ?? '', local_user());
82 $result = new ContactResult(
83 $user_data['name'] ?? '',
84 $user_data['addr'] ?? '',
85 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
86 $user_data['url'] ?? '',
87 $user_data['photo'] ?? '',
88 $user_data['network'] ?? '',
89 $contactDetails['id'] ?? 0,
91 $user_data['tags'] ?? ''
94 return new ResultList(1, 1, 1, [$result]);
96 return $emptyResultList;
101 * Search in the global directory for occurrences of the search string
103 * @see https://github.com/friendica/friendica-directory/blob/master/docs/Protocol.md#search
105 * @param string $search
106 * @param int $type specific type of searching
110 * @throws HTTPException\InternalServerErrorException
112 public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
114 $server = DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
116 $searchUrl = $server . '/search';
119 case self::TYPE_FORUM:
120 $searchUrl .= '/forum';
122 case self::TYPE_PEOPLE:
123 $searchUrl .= '/people';
126 $searchUrl .= '?q=' . urlencode($search);
129 $searchUrl .= '&page=' . $page;
132 $resultJson = Network::fetchUrl($searchUrl, false, 0, 'application/json');
134 $results = json_decode($resultJson, true);
136 $resultList = new ResultList(
137 ($results['page'] ?? 0) ?: 1,
138 $results['count'] ?? 0,
139 ($results['itemsperpage'] ?? 0) ?: 30
142 $profiles = $results['profiles'] ?? [];
144 foreach ($profiles as $profile) {
145 $profile_url = $profile['url'] ?? '';
146 $contactDetails = Contact::getDetailsByURL($profile_url, local_user());
148 $result = new ContactResult(
149 $profile['name'] ?? '',
150 $profile['addr'] ?? '',
151 ($contactDetails['addr'] ?? '') ?: $profile_url,
153 $profile['photo'] ?? '',
155 $contactDetails['cid'] ?? 0,
157 $profile['tags'] ?? ''
160 $resultList->addResult($result);
167 * Search in the local database for occurrences of the search string
169 * @param string $search
172 * @param int $itemPage
175 * @throws HTTPException\InternalServerErrorException
177 public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
179 $config = DI::config();
181 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
182 $ostatus = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
184 $wildcard = Strings::escapeHtml('%' . $search . '%');
186 $count = DBA::count('gcontact', [
188 AND `network` IN (?, ?, ?, ?)
189 AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
190 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
191 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
192 AND `community` = ?',
193 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
194 $wildcard, $wildcard, $wildcard,
195 $wildcard, $wildcard, $wildcard,
196 ($type === self::TYPE_FORUM),
199 $resultList = new ResultList($start, $itemPage, $count);
205 $data = DBA::select('gcontact', ['nurl'], [
207 AND `network` IN (?, ?, ?, ?)
208 AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
209 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
210 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
211 AND `community` = ?',
212 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
213 $wildcard, $wildcard, $wildcard,
214 $wildcard, $wildcard, $wildcard,
215 ($type === self::TYPE_FORUM),
217 'group_by' => ['nurl', 'updated'],
218 'limit' => [$start, $itemPage],
219 'order' => ['updated' => 'DESC']
222 if (!DBA::isResult($data)) {
226 while ($row = DBA::fetch($data)) {
227 $urlParts = parse_url($row["nurl"]);
229 // Ignore results that look strange.
230 // For historic reasons the gcontact table does contain some garbage.
231 if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
235 $contact = Contact::getDetailsByURL($row["nurl"], local_user());
237 if ($contact["name"] == "") {
238 $contact["name"] = end(explode("/", $urlParts["path"]));
241 $result = new ContactResult(
253 $resultList->addResult($result);
258 // Add found profiles from the global directory to the local directory
259 Worker::add(PRIORITY_LOW, 'SearchDirectory', $search);
265 * Searching for global contacts for autocompletion
267 * @param string $search Name or part of a name or nick
268 * @param string $mode Search mode (e.g. "community")
269 * @param int $page Page number (starts at 1)
270 * @return array with the search results
271 * @throws HTTPException\InternalServerErrorException
273 public static function searchGlobalContact($search, $mode, int $page = 1)
275 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
279 // don't search if search term has less than 2 characters
280 if (!$search || mb_strlen($search) < 2) {
284 if (substr($search, 0, 1) === '@') {
285 $search = substr($search, 1);
288 // check if searching in the local global contact table is enabled
289 if (DI::config()->get('system', 'poco_local_search')) {
290 $return = GContact::searchByName($search, $mode);
292 $p = $page > 1 ? 'p=' . $page : '';
293 $curlResult = Network::curl(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
294 if ($curlResult->isSuccess()) {
295 $searchResult = json_decode($curlResult->getBody(), true);
296 if (!empty($searchResult['profiles'])) {
297 $return = $searchResult['profiles'];
302 return $return ?? [];
306 * Returns the global directory name, used in this node
310 public static function getGlobalDirectory()
312 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);