3 namespace Friendica\Core;
5 use Friendica\BaseObject;
6 use Friendica\Database\DBA;
7 use Friendica\Model\Contact;
8 use Friendica\Model\GContact;
9 use Friendica\Network\HTTPException;
10 use Friendica\Network\Probe;
11 use Friendica\Object\Search\ContactResult;
12 use Friendica\Object\Search\ResultList;
13 use Friendica\Protocol\PortableContact;
14 use Friendica\Util\Network;
15 use Friendica\Util\Strings;
18 * Specific class to perform searches for different systems. Currently:
19 * - Probe for contacts
20 * - Search in the local directory
21 * - Search in the global directory
23 class Search extends BaseObject
25 const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
27 const TYPE_PEOPLE = 0;
32 * Search a user based on his/her profile address
33 * pattern: @username@domain.tld
35 * @param string $user The user to search for
38 * @throws HTTPException\InternalServerErrorException
39 * @throws \ImagickException
41 public static function getContactsFromProbe($user)
43 $emptyResultList = new ResultList(1, 0, 1);
45 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
46 (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
48 /// @todo Possibly use "getIdForURL" instead?
49 $user_data = Probe::uri($user);
50 if (empty($user_data)) {
51 return $emptyResultList;
54 if (!in_array($user_data["network"], Protocol::FEDERATED)) {
55 return $emptyResultList;
58 // Ensure that we do have a contact entry
59 Contact::getIdForURL($user_data['url'] ?? '');
61 $contactDetails = Contact::getDetailsByURL($user_data['url'] ?? '', local_user());
63 $result = new ContactResult(
64 $user_data['name'] ?? '',
65 $user_data['addr'] ?? '',
66 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
67 $user_data['url'] ?? '',
68 $user_data['photo'] ?? '',
69 $user_data['network'] ?? '',
70 $contactDetails['id'] ?? 0,
72 $user_data['tags'] ?? ''
75 return new ResultList(1, 1, 1, [$result]);
77 return $emptyResultList;
82 * Search in the global directory for occurrences of the search string
84 * @see https://github.com/friendica/friendica-directory/blob/master/docs/Protocol.md#search
86 * @param string $search
87 * @param int $type specific type of searching
91 * @throws HTTPException\InternalServerErrorException
93 public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
95 $config = self::getApp()->getConfig();
96 $server = $config->get('system', 'directory', self::DEFAULT_DIRECTORY);
98 $searchUrl = $server . '/search';
101 case self::TYPE_FORUM:
102 $searchUrl .= '/forum';
104 case self::TYPE_PEOPLE:
105 $searchUrl .= '/people';
108 $searchUrl .= '?q=' . urlencode($search);
111 $searchUrl .= '&page=' . $page;
114 $resultJson = Network::fetchUrl($searchUrl, false, 0, 'application/json');
116 $results = json_decode($resultJson, true);
118 $resultList = new ResultList(
119 ($results['page'] ?? 0) ?: 1,
120 $results['count'] ?? 0,
121 ($results['itemsperpage'] ?? 0) ?: 30
124 $profiles = $results['profiles'] ?? [];
126 foreach ($profiles as $profile) {
127 $profile_url = $profile['profile_url'] ?? '';
128 $contactDetails = Contact::getDetailsByURL($profile_url, local_user());
130 $result = new ContactResult(
131 $profile['name'] ?? '',
132 $profile['addr'] ?? '',
133 ($contactDetails['addr'] ?? '') ?: $profile_url,
135 $profile['photo'] ?? '',
137 $contactDetails['cid'] ?? 0,
139 $profile['tags'] ?? ''
142 $resultList->addResult($result);
149 * Search in the local database for occurrences of the search string
151 * @param string $search
154 * @param int $itemPage
157 * @throws HTTPException\InternalServerErrorException
159 public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
161 $config = self::getApp()->getConfig();
163 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
164 $ostatus = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
166 $wildcard = Strings::escapeHtml('%' . $search . '%');
168 $count = DBA::count('gcontact', [
170 AND `network` IN (?, ?, ?, ?)
171 AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
172 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
173 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
174 AND `community` = ?',
175 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
176 $wildcard, $wildcard, $wildcard,
177 $wildcard, $wildcard, $wildcard,
178 ($type === self::TYPE_FORUM),
181 $resultList = new ResultList($start, $itemPage, $count);
187 $data = DBA::select('gcontact', ['nurl'], [
189 AND `network` IN (?, ?, ?, ?)
190 AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
191 AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ?
192 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
193 AND `community` = ?',
194 Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
195 $wildcard, $wildcard, $wildcard,
196 $wildcard, $wildcard, $wildcard,
197 ($type === self::TYPE_FORUM),
199 'group_by' => ['nurl', 'updated'],
200 'limit' => [$start, $itemPage],
201 'order' => ['updated' => 'DESC']
204 if (!DBA::isResult($data)) {
208 while ($row = DBA::fetch($data)) {
209 if (PortableContact::alternateOStatusUrl($row["nurl"])) {
213 $urlParts = parse_url($row["nurl"]);
215 // Ignore results that look strange.
216 // For historic reasons the gcontact table does contain some garbage.
217 if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
221 $contact = Contact::getDetailsByURL($row["nurl"], local_user());
223 if ($contact["name"] == "") {
224 $contact["name"] = end(explode("/", $urlParts["path"]));
227 $result = new ContactResult(
239 $resultList->addResult($result);
244 // Add found profiles from the global directory to the local directory
245 Worker::add(PRIORITY_LOW, 'DiscoverPoCo', "dirsearch", urlencode($search));
251 * Searching for global contacts for autocompletion
253 * @brief Searching for global contacts for autocompletion
254 * @param string $search Name or part of a name or nick
255 * @param string $mode Search mode (e.g. "community")
256 * @param int $page Page number (starts at 1)
257 * @return array with the search results
258 * @throws HTTPException\InternalServerErrorException
260 public static function searchGlobalContact($search, $mode, int $page = 1)
262 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
266 // don't search if search term has less than 2 characters
267 if (!$search || mb_strlen($search) < 2) {
271 if (substr($search, 0, 1) === '@') {
272 $search = substr($search, 1);
275 // check if searching in the local global contact table is enabled
276 if (Config::get('system', 'poco_local_search')) {
277 $return = GContact::searchByName($search, $mode);
279 $p = $page > 1 ? 'p=' . $page : '';
280 $curlResult = Network::curl(get_server() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
281 if ($curlResult->isSuccess()) {
282 $searchResult = json_decode($curlResult->getBody(), true);
283 if (!empty($searchResult['profiles'])) {
284 $return = $searchResult['profiles'];
289 return $return ?? [];