]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
Merge pull request #13183 from MrPetovan/task/13114-rename-forum-to-group
[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_GROUP  = 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, $only_group = false): ResultList
59         {
60                 $emptyResultList = new ResultList();
61
62                 if (empty(parse_url($user, PHP_URL_SCHEME)) && !(filter_var($user, FILTER_VALIDATE_EMAIL) || Network::isEmailDomainValid($user))) {
63                         return $emptyResultList;
64                 }
65
66                 $user_data = Contact::getByURL($user);
67                 if (empty($user_data)) {
68                         return $emptyResultList;
69                 }
70
71                 if ($only_group && ($user_data['contact-type'] != Contact::TYPE_COMMUNITY)) {
72                         return $emptyResultList;
73                 }
74
75                 if (!Protocol::supportsProbe($user_data['network'])) {
76                         return $emptyResultList;
77                 }
78
79                 $contactDetails = Contact::getByURLForUser($user_data['url'], DI::userSession()->getLocalUserId());
80
81                 $result = new ContactResult(
82                         $user_data['name'],
83                         $user_data['addr'],
84                         $user_data['addr'] ?: $user_data['url'],
85                         new Uri($user_data['url']),
86                         $user_data['photo'],
87                         $user_data['network'],
88                         $contactDetails['cid'] ?? 0,
89                         $user_data['id'],
90                         $user_data['keywords']
91                 );
92
93                 return new ResultList(1, 1, 1, [$result]);
94         }
95
96         /**
97          * Search in the global directory for occurrences of the search string
98          *
99          * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
100          *
101          * @param string $search
102          * @param int    $type specific type of searching
103          * @param int    $page
104          *
105          * @return ResultList
106          * @throws HTTPException\InternalServerErrorException
107          */
108         public static function getContactsFromGlobalDirectory(string $search, int $type = self::TYPE_ALL, int $page = 1): ResultList
109         {
110                 $server = self::getGlobalDirectory();
111
112                 $searchUrl = $server . '/search';
113
114                 switch ($type) {
115                         case self::TYPE_GROUP:
116                                 $searchUrl .= '/group';
117                                 break;
118                         case self::TYPE_PEOPLE:
119                                 $searchUrl .= '/people';
120                                 break;
121                 }
122                 $searchUrl .= '?q=' . urlencode($search);
123
124                 if ($page > 1) {
125                         $searchUrl .= '&page=' . $page;
126                 }
127
128                 $resultJson = DI::httpClient()->fetch($searchUrl, HttpClientAccept::JSON);
129
130                 $results = json_decode($resultJson, true);
131
132                 $resultList = new ResultList(
133                         ($results['page']         ?? 0) ?: 1,
134                         $results['count']        ?? 0,
135                         ($results['itemsperpage'] ?? 0) ?: 30
136                 );
137
138                 $profiles = $results['profiles'] ?? [];
139
140                 foreach ($profiles as $profile) {
141                         $profile_url = $profile['profile_url'] ?? '';
142                         $contactDetails = Contact::getByURLForUser($profile_url, DI::userSession()->getLocalUserId());
143
144                         $result = new ContactResult(
145                                 $profile['name'] ?? '',
146                                 $profile['addr'] ?? '',
147                                 ($contactDetails['addr'] ?? '') ?: $profile_url,
148                                 new Uri($profile_url),
149                                 $profile['photo'] ?? '',
150                                 Protocol::DFRN,
151                                 $contactDetails['cid'] ?? 0,
152                                 $contactDetails['zid'] ?? 0,
153                                 $profile['tags'] ?? ''
154                         );
155
156                         $resultList->addResult($result);
157                 }
158
159                 return $resultList;
160         }
161
162         /**
163          * Search in the local database for occurrences of the search string
164          *
165          * @param string $search
166          * @param int    $type
167          * @param int    $start
168          * @param int    $itemPage
169          *
170          * @return ResultList
171          * @throws HTTPException\InternalServerErrorException
172          */
173         public static function getContactsFromLocalDirectory(string $search, int $type = self::TYPE_ALL, int $start = 0, int $itemPage = 80): ResultList
174         {
175                 Logger::info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]);
176
177                 $contacts = Contact::searchByName($search, $type == self::TYPE_GROUP ? 'community' : '', true);
178
179                 $resultList = new ResultList($start, count($contacts), $itemPage);
180
181                 foreach ($contacts as $contact) {
182                         $result = new ContactResult(
183                                 $contact['name'],
184                                 $contact['addr'],
185                                 $contact['addr'] ?: $contact['url'],
186                                 new Uri($contact['url']),
187                                 $contact['photo'],
188                                 $contact['network'],
189                                 0,
190                                 $contact['pid'],
191                                 $contact['keywords']
192                         );
193
194                         $resultList->addResult($result);
195                 }
196
197                 // Add found profiles from the global directory to the local directory
198                 Worker::add(Worker::PRIORITY_LOW, 'SearchDirectory', $search);
199
200                 return $resultList;
201         }
202
203         /**
204          * Searching for contacts for autocompletion
205          *
206          * @param string $search Name or part of a name or nick
207          * @param string $mode   Search mode (e.g. "community")
208          * @param int    $page   Page number (starts at 1)
209          *
210          * @return array with the search results or empty if error or nothing found
211          * @throws HTTPException\InternalServerErrorException
212          */
213         public static function searchContact(string $search, string $mode, int $page = 1): array
214         {
215                 Logger::info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]);
216
217                 if (DI::config()->get('system', 'block_public') && !DI::userSession()->isAuthenticated()) {
218                         return [];
219                 }
220
221                 // don't search if search term has less than 2 characters
222                 if (!$search || mb_strlen($search) < 2) {
223                         return [];
224                 }
225
226                 if (substr($search, 0, 1) === '@') {
227                         $search = substr($search, 1);
228                 }
229
230                 // check if searching in the local global contact table is enabled
231                 if (DI::config()->get('system', 'poco_local_search')) {
232                         $return = Contact::searchByName($search, $mode, true);
233                 } else {
234                         $p = $page > 1 ? 'p=' . $page : '';
235                         $curlResult = DI::httpClient()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), HttpClientAccept::JSON);
236                         if ($curlResult->isSuccess()) {
237                                 $searchResult = json_decode($curlResult->getBody(), true);
238                                 if (!empty($searchResult['profiles'])) {
239                                         // Converting Directory Search results into contact-looking records
240                                         $return = array_map(function ($result) {
241                                                 static $contactType = [
242                                                         'People'       => Contact::TYPE_PERSON,
243                                                         // Kept for backward compatibility
244                                                         'Forum'        => Contact::TYPE_COMMUNITY,
245                                                         'Group'        => Contact::TYPE_COMMUNITY,
246                                                         'Organization' => Contact::TYPE_ORGANISATION,
247                                                         'News'         => Contact::TYPE_NEWS,
248                                                 ];
249
250                                                 return [
251                                                         'name'         => $result['name'],
252                                                         'addr'         => $result['addr'],
253                                                         'url'          => $result['profile_url'],
254                                                         'network'      => Protocol::DFRN,
255                                                         'micro'        => $result['photo'],
256                                                         'contact-type' => $contactType[$result['account_type']],
257                                                 ];
258                                         }, $searchResult['profiles']);
259                                 }
260                         }
261                 }
262
263                 return $return ?? [];
264         }
265
266         /**
267          * Returns the global directory name, used in this node
268          *
269          * @return string
270          */
271         public static function getGlobalDirectory(): string
272         {
273                 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
274         }
275
276         /**
277          * Return the search path (either fulltext search or tag search)
278          *
279          * @param string $search
280          *
281          * @return string search path
282          */
283         public static function getSearchPath(string $search): string
284         {
285                 if (substr($search, 0, 1) == '#') {
286                         return 'search?tag=' . urlencode(substr($search, 1));
287                 } else {
288                         return 'search?q=' . urlencode($search);
289                 }
290         }
291 }