]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
Merge remote-tracking branch 'upstream/develop' into search
[friendica.git] / src / Core / Search.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Core;
23
24 use Friendica\DI;
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;
33
34 /**
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
39  */
40 class Search
41 {
42         const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
43
44         const TYPE_PEOPLE = 0;
45         const TYPE_FORUM  = 1;
46         const TYPE_ALL    = 2;
47
48         /**
49          * Search a user based on his/her profile address
50          * pattern: @username@domain.tld
51          *
52          * @param string $user The user to search for
53          *
54          * @return ResultList
55          * @throws HTTPException\InternalServerErrorException
56          * @throws \ImagickException
57          */
58         public static function getContactsFromProbe(string $user): ?ResultList
59         {
60                 if (empty(parse_url($user, PHP_URL_SCHEME)) && !(filter_var($user, FILTER_VALIDATE_EMAIL) || Network::isEmailDomainValid($user))) {
61                         return null;            
62                 }
63         
64                 $user_data = Contact::getByURL($user);
65                 if (empty($user_data)) {
66                         return null;
67                 }
68
69                 if (!Protocol::supportsProbe($user_data['network'])) {
70                         return null;
71                 }
72
73                 $contactDetails = Contact::getByURLForUser($user_data['url'], DI::userSession()->getLocalUserId());
74
75                 $result = new ContactResult(
76                         $user_data['name'],
77                         $user_data['addr'],
78                         $user_data['addr'] ?: $user_data['url'],
79                         new Uri($user_data['url']),
80                         $user_data['photo'],
81                         $user_data['network'],
82                         $contactDetails['cid'] ?? 0,
83                         $user_data['id'],
84                         $user_data['tags']
85                 );
86
87                 return new ResultList(1, 1, 1, [$result]);
88         }
89
90         /**
91          * Search in the global directory for occurrences of the search string
92          *
93          * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
94          *
95          * @param string $search
96          * @param int    $type specific type of searching
97          * @param int    $page
98          *
99          * @return ResultList
100          * @throws HTTPException\InternalServerErrorException
101          */
102         public static function getContactsFromGlobalDirectory(string $search, int $type = self::TYPE_ALL, int $page = 1): ResultList
103         {
104                 $server = self::getGlobalDirectory();
105
106                 $searchUrl = $server . '/search';
107
108                 switch ($type) {
109                         case self::TYPE_FORUM:
110                                 $searchUrl .= '/forum';
111                                 break;
112                         case self::TYPE_PEOPLE:
113                                 $searchUrl .= '/people';
114                                 break;
115                 }
116                 $searchUrl .= '?q=' . urlencode($search);
117
118                 if ($page > 1) {
119                         $searchUrl .= '&page=' . $page;
120                 }
121
122                 $resultJson = DI::httpClient()->fetch($searchUrl, HttpClientAccept::JSON);
123
124                 $results = json_decode($resultJson, true);
125
126                 $resultList = new ResultList(
127                         ($results['page']         ?? 0) ?: 1,
128                          $results['count']        ?? 0,
129                         ($results['itemsperpage'] ?? 0) ?: 30
130                 );
131
132                 $profiles = $results['profiles'] ?? [];
133
134                 foreach ($profiles as $profile) {
135                         $profile_url = $profile['profile_url'] ?? '';
136                         $contactDetails = Contact::getByURLForUser($profile_url, DI::userSession()->getLocalUserId());
137
138                         $result = new ContactResult(
139                                 $profile['name'] ?? '',
140                                 $profile['addr'] ?? '',
141                                 ($contactDetails['addr'] ?? '') ?: $profile_url,
142                                 new Uri($profile_url),
143                                 $profile['photo'] ?? '',
144                                 Protocol::DFRN,
145                                 $contactDetails['cid'] ?? 0,
146                                 $contactDetails['zid'] ?? 0,
147                                 $profile['tags'] ?? ''
148                         );
149
150                         $resultList->addResult($result);
151                 }
152
153                 return $resultList;
154         }
155
156         /**
157          * Search in the local database for occurrences of the search string
158          *
159          * @param string $search
160          * @param int    $type
161          * @param int    $start
162          * @param int    $itemPage
163          *
164          * @return ResultList
165          * @throws HTTPException\InternalServerErrorException
166          */
167         public static function getContactsFromLocalDirectory(string $search, int $type = self::TYPE_ALL, int $start = 0, int $itemPage = 80): ResultList
168         {
169                 Logger::info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]);
170
171                 $contacts = Contact::searchByName($search, $type == self::TYPE_FORUM ? 'community' : '', true);
172
173                 $resultList = new ResultList($start, $itemPage, count($contacts));
174
175                 foreach ($contacts as $contact) {
176                         $result = new ContactResult(
177                                 $contact['name'],
178                                 $contact['addr'],
179                                 $contact['addr'] ?: $contact['url'],
180                                 new Uri($contact['url']),
181                                 $contact['photo'],
182                                 $contact['network'],
183                                 0,
184                                 $contact['pid'],
185                                 $contact['keywords']
186                         );
187
188                         $resultList->addResult($result);
189                 }
190
191                 // Add found profiles from the global directory to the local directory
192                 Worker::add(Worker::PRIORITY_LOW, 'SearchDirectory', $search);
193
194                 return $resultList;
195         }
196
197         /**
198          * Searching for contacts for autocompletion
199          *
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)
203          *
204          * @return array with the search results or empty if error or nothing found
205          * @throws HTTPException\InternalServerErrorException
206          */
207         public static function searchContact(string $search, string $mode, int $page = 1): array
208         {
209                 Logger::info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]);
210
211                 if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
212                         return [];
213                 }
214
215                 // don't search if search term has less than 2 characters
216                 if (!$search || mb_strlen($search) < 2) {
217                         return [];
218                 }
219
220                 if (substr($search, 0, 1) === '@') {
221                         $search = substr($search, 1);
222                 }
223
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);
227                 } else {
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,
240                                                 ];
241
242                                                 return [
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']],
249                                                 ];
250                                         }, $searchResult['profiles']);
251                                 }
252                         }
253                 }
254
255                 return $return ?? [];
256         }
257
258         /**
259          * Returns the global directory name, used in this node
260          *
261          * @return string
262          */
263         public static function getGlobalDirectory(): string
264         {
265                 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
266         }
267
268         /**
269          * Return the search path (either fulltext search or tag search)
270          *
271          * @param string $search
272          *
273          * @return string search path
274          */
275         public static function getSearchPath(string $search): string
276         {
277                 if (substr($search, 0, 1) == '#') {
278                         return 'search?tag=' . urlencode(substr($search, 1));
279                 } else {
280                         return 'search?q=' . urlencode($search);
281                 }
282         }
283 }