]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
ff1a8a317c8227264468821bb4f1694e0617a7ca
[friendica.git] / src / Core / Search.php
1 <?php
2
3 namespace Friendica\Core;
4
5 use Friendica\BaseObject;
6 use Friendica\Database\DBA;
7 use Friendica\DI;
8 use Friendica\Model\Contact;
9 use Friendica\Model\GContact;
10 use Friendica\Network\HTTPException;
11 use Friendica\Network\Probe;
12 use Friendica\Object\Search\ContactResult;
13 use Friendica\Object\Search\ResultList;
14 use Friendica\Protocol\PortableContact;
15 use Friendica\Util\Network;
16 use Friendica\Util\Strings;
17
18 /**
19  * Specific class to perform searches for different systems. Currently:
20  * - Probe for contacts
21  * - Search in the local directory
22  * - Search in the global directory
23  */
24 class Search extends BaseObject
25 {
26         const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
27
28         const TYPE_PEOPLE = 0;
29         const TYPE_FORUM  = 1;
30         const TYPE_ALL    = 2;
31
32         /**
33          * Search a user based on his/her profile address
34          * pattern: @username@domain.tld
35          *
36          * @param string $user The user to search for
37          *
38          * @return ResultList
39          * @throws HTTPException\InternalServerErrorException
40          * @throws \ImagickException
41          */
42         public static function getContactsFromProbe($user)
43         {
44                 $emptyResultList = new ResultList(1, 0, 1);
45
46                 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
47                     (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
48
49                         /// @todo Possibly use "getIdForURL" instead?
50                         $user_data = Probe::uri($user);
51                         if (empty($user_data)) {
52                                 return $emptyResultList;
53                         }
54
55                         if (!in_array($user_data["network"], Protocol::FEDERATED)) {
56                                 return $emptyResultList;
57                         }
58
59                         // Ensure that we do have a contact entry
60                         Contact::getIdForURL($user_data['url'] ?? '');
61
62                         $contactDetails = Contact::getDetailsByURL($user_data['url'] ?? '', local_user());
63
64                         $result = new ContactResult(
65                                 $user_data['name'] ?? '',
66                                 $user_data['addr'] ?? '',
67                                 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
68                                 $user_data['url'] ?? '',
69                                 $user_data['photo'] ?? '',
70                                 $user_data['network'] ?? '',
71                                 $contactDetails['id'] ?? 0,
72                                 0,
73                                 $user_data['tags'] ?? ''
74                         );
75
76                         return new ResultList(1, 1, 1, [$result]);
77                 } else {
78                         return $emptyResultList;
79                 }
80         }
81
82         /**
83          * Search in the global directory for occurrences of the search string
84          *
85          * @see https://github.com/friendica/friendica-directory/blob/master/docs/Protocol.md#search
86          *
87          * @param string $search
88          * @param int    $type specific type of searching
89          * @param int    $page
90          *
91          * @return ResultList
92          * @throws HTTPException\InternalServerErrorException
93          */
94         public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
95         {
96                 $config = DI::app()->getConfig();
97                 $server = $config->get('system', 'directory', self::DEFAULT_DIRECTORY);
98
99                 $searchUrl = $server . '/search';
100
101                 switch ($type) {
102                         case self::TYPE_FORUM:
103                                 $searchUrl .= '/forum';
104                                 break;
105                         case self::TYPE_PEOPLE:
106                                 $searchUrl .= '/people';
107                                 break;
108                 }
109                 $searchUrl .= '?q=' . urlencode($search);
110
111                 if ($page > 1) {
112                         $searchUrl .= '&page=' . $page;
113                 }
114
115                 $resultJson = Network::fetchUrl($searchUrl, false, 0, 'application/json');
116
117                 $results = json_decode($resultJson, true);
118
119                 $resultList = new ResultList(
120                         ($results['page']         ?? 0) ?: 1,
121                          $results['count']        ?? 0,
122                         ($results['itemsperpage'] ?? 0) ?: 30
123                 );
124
125                 $profiles = $results['profiles'] ?? [];
126
127                 foreach ($profiles as $profile) {
128                         $profile_url = $profile['profile_url'] ?? '';
129                         $contactDetails = Contact::getDetailsByURL($profile_url, local_user());
130
131                         $result = new ContactResult(
132                                 $profile['name'] ?? '',
133                                 $profile['addr'] ?? '',
134                                 ($contactDetails['addr'] ?? '') ?: $profile_url,
135                                 $profile_url,
136                                 $profile['photo'] ?? '',
137                                 Protocol::DFRN,
138                                 $contactDetails['cid'] ?? 0,
139                                 0,
140                                 $profile['tags'] ?? ''
141                         );
142
143                         $resultList->addResult($result);
144                 }
145
146                 return $resultList;
147         }
148
149         /**
150          * Search in the local database for occurrences of the search string
151          *
152          * @param string $search
153          * @param int    $type
154          * @param int    $start
155          * @param int    $itemPage
156          *
157          * @return ResultList
158          * @throws HTTPException\InternalServerErrorException
159          */
160         public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
161         {
162                 $config = DI::app()->getConfig();
163
164                 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
165                 $ostatus  = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
166
167                 $wildcard = Strings::escapeHtml('%' . $search . '%');
168
169                 $count = DBA::count('gcontact', [
170                         'NOT `hide`
171                         AND `network` IN (?, ?, ?, ?)
172                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
173                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
174                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
175                         AND `community` = ?',
176                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
177                         $wildcard, $wildcard, $wildcard,
178                         $wildcard, $wildcard, $wildcard,
179                         ($type === self::TYPE_FORUM),
180                 ]);
181
182                 $resultList = new ResultList($start, $itemPage, $count);
183
184                 if (empty($count)) {
185                         return $resultList;
186                 }
187
188                 $data = DBA::select('gcontact', ['nurl'], [
189                         'NOT `hide`
190                         AND `network` IN (?, ?, ?, ?)
191                         AND ((`last_contact` >= `last_failure`) OR (`updated` >= `last_failure`))
192                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
193                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
194                         AND `community` = ?',
195                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
196                         $wildcard, $wildcard, $wildcard,
197                         $wildcard, $wildcard, $wildcard,
198                         ($type === self::TYPE_FORUM),
199                 ], [
200                         'group_by' => ['nurl', 'updated'],
201                         'limit'    => [$start, $itemPage],
202                         'order'    => ['updated' => 'DESC']
203                 ]);
204
205                 if (!DBA::isResult($data)) {
206                         return $resultList;
207                 }
208
209                 while ($row = DBA::fetch($data)) {
210                         if (PortableContact::alternateOStatusUrl($row["nurl"])) {
211                                 continue;
212                         }
213
214                         $urlParts = parse_url($row["nurl"]);
215
216                         // Ignore results that look strange.
217                         // For historic reasons the gcontact table does contain some garbage.
218                         if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
219                                 continue;
220                         }
221
222                         $contact = Contact::getDetailsByURL($row["nurl"], local_user());
223
224                         if ($contact["name"] == "") {
225                                 $contact["name"] = end(explode("/", $urlParts["path"]));
226                         }
227
228                         $result = new ContactResult(
229                                 $contact["name"],
230                                 $contact["addr"],
231                                 $contact["addr"],
232                                 $contact["url"],
233                                 $contact["photo"],
234                                 $contact["network"],
235                                 $contact["cid"],
236                                 $contact["zid"],
237                                 $contact["keywords"]
238                         );
239
240                         $resultList->addResult($result);
241                 }
242
243                 DBA::close($data);
244
245                 // Add found profiles from the global directory to the local directory
246                 Worker::add(PRIORITY_LOW, 'SearchDirectory', $search);
247
248                 return $resultList;
249         }
250
251         /**
252          * Searching for global contacts for autocompletion
253          *
254          * @brief Searching for global contacts for autocompletion
255          * @param string $search Name or part of a name or nick
256          * @param string $mode   Search mode (e.g. "community")
257          * @param int    $page   Page number (starts at 1)
258          * @return array with the search results
259          * @throws HTTPException\InternalServerErrorException
260          */
261         public static function searchGlobalContact($search, $mode, int $page = 1)
262         {
263                 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
264                         return [];
265                 }
266
267                 // don't search if search term has less than 2 characters
268                 if (!$search || mb_strlen($search) < 2) {
269                         return [];
270                 }
271
272                 if (substr($search, 0, 1) === '@') {
273                         $search = substr($search, 1);
274                 }
275
276                 // check if searching in the local global contact table is enabled
277                 if (Config::get('system', 'poco_local_search')) {
278                         $return = GContact::searchByName($search, $mode);
279                 } else {
280                         $p = $page > 1 ? 'p=' . $page : '';
281                         $curlResult = Network::curl(get_server() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
282                         if ($curlResult->isSuccess()) {
283                                 $searchResult = json_decode($curlResult->getBody(), true);
284                                 if (!empty($searchResult['profiles'])) {
285                                         $return = $searchResult['profiles'];
286                                 }
287                         }
288                 }
289
290                 return $return ?? [];
291         }
292 }