]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
Merge pull request #10209 from MrPetovan/bug/10205-frio-link-preview-accents
[friendica.git] / src / Core / Search.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\HTTPException;
27 use Friendica\Object\Search\ContactResult;
28 use Friendica\Object\Search\ResultList;
29 use Friendica\Util\Network;
30 use Friendica\Util\Strings;
31
32 /**
33  * Specific class to perform searches for different systems. Currently:
34  * - Probe for contacts
35  * - Search in the local directory
36  * - Search in the global directory
37  */
38 class Search
39 {
40         const DEFAULT_DIRECTORY = 'https://dir.friendica.social';
41
42         const TYPE_PEOPLE = 0;
43         const TYPE_FORUM  = 1;
44         const TYPE_ALL    = 2;
45
46         /**
47          * Search a user based on his/her profile address
48          * pattern: @username@domain.tld
49          *
50          * @param string $user The user to search for
51          *
52          * @return ResultList
53          * @throws HTTPException\InternalServerErrorException
54          * @throws \ImagickException
55          */
56         public static function getContactsFromProbe($user)
57         {
58                 $emptyResultList = new ResultList(1, 0, 1);
59
60                 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
61                     (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
62
63                         $user_data = Contact::getByURL($user);
64                         if (empty($user_data)) {
65                                 return $emptyResultList;
66                         }
67
68                         if (!in_array($user_data["network"], Protocol::FEDERATED)) {
69                                 return $emptyResultList;
70                         }
71
72                         $contactDetails = Contact::getByURLForUser($user_data['url'] ?? '', local_user());
73
74                         $result = new ContactResult(
75                                 $user_data['name'] ?? '',
76                                 $user_data['addr'] ?? '',
77                                 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
78                                 $user_data['url'] ?? '',
79                                 $user_data['photo'] ?? '',
80                                 $user_data['network'] ?? '',
81                                 $contactDetails['id'] ?? 0,
82                                 $user_data['id'] ?? 0,
83                                 $user_data['tags'] ?? ''
84                         );
85
86                         return new ResultList(1, 1, 1, [$result]);
87                 } else {
88                         return $emptyResultList;
89                 }
90         }
91
92         /**
93          * Search in the global directory for occurrences of the search string
94          *
95          * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
96          *
97          * @param string $search
98          * @param int    $type specific type of searching
99          * @param int    $page
100          *
101          * @return ResultList
102          * @throws HTTPException\InternalServerErrorException
103          */
104         public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
105         {
106                 $server = DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
107
108                 $searchUrl = $server . '/search';
109
110                 switch ($type) {
111                         case self::TYPE_FORUM:
112                                 $searchUrl .= '/forum';
113                                 break;
114                         case self::TYPE_PEOPLE:
115                                 $searchUrl .= '/people';
116                                 break;
117                 }
118                 $searchUrl .= '?q=' . urlencode($search);
119
120                 if ($page > 1) {
121                         $searchUrl .= '&page=' . $page;
122                 }
123
124                 $resultJson = DI::httpRequest()->fetch($searchUrl, 0, 'application/json');
125
126                 $results = json_decode($resultJson, true);
127
128                 $resultList = new ResultList(
129                         ($results['page']         ?? 0) ?: 1,
130                          $results['count']        ?? 0,
131                         ($results['itemsperpage'] ?? 0) ?: 30
132                 );
133
134                 $profiles = $results['profiles'] ?? [];
135
136                 foreach ($profiles as $profile) {
137                         $profile_url = $profile['profile_url'] ?? '';
138                         $contactDetails = Contact::getByURLForUser($profile_url, local_user());
139
140                         $result = new ContactResult(
141                                 $profile['name'] ?? '',
142                                 $profile['addr'] ?? '',
143                                 ($contactDetails['addr'] ?? '') ?: $profile_url,
144                                 $profile_url,
145                                 $profile['photo'] ?? '',
146                                 Protocol::DFRN,
147                                 $contactDetails['cid'] ?? 0,
148                                 0,
149                                 $profile['tags'] ?? ''
150                         );
151
152                         $resultList->addResult($result);
153                 }
154
155                 return $resultList;
156         }
157
158         /**
159          * Search in the local database for occurrences of the search string
160          *
161          * @param string $search
162          * @param int    $type
163          * @param int    $start
164          * @param int    $itemPage
165          *
166          * @return ResultList
167          * @throws HTTPException\InternalServerErrorException
168          */
169         public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
170         {
171                 Logger::info('Searching', ['search' => $search, 'type' => $type, 'start' => $start, 'itempage' => $itemPage]);
172
173                 $contacts = Contact::searchByName($search, $type == self::TYPE_FORUM ? 'community' : '');
174
175                 $resultList = new ResultList($start, $itemPage, count($contacts));
176
177                 foreach ($contacts as $contact) {
178                         $result = new ContactResult(
179                                 $contact["name"],
180                                 $contact["addr"],
181                                 $contact["addr"],
182                                 $contact["url"],
183                                 $contact["photo"],
184                                 $contact["network"],
185                                 $contact["cid"] ?? 0,
186                                 $contact["zid"] ?? 0,
187                                 $contact["keywords"]
188                         );
189
190                         $resultList->addResult($result);
191                 }
192
193                 // Add found profiles from the global directory to the local directory
194                 Worker::add(PRIORITY_LOW, 'SearchDirectory', $search);
195
196                 return $resultList;
197         }
198
199         /**
200          * Searching for contacts for autocompletion
201          *
202          * @param string $search Name or part of a name or nick
203          * @param string $mode   Search mode (e.g. "community")
204          * @param int    $page   Page number (starts at 1)
205          * @return array with the search results
206          * @throws HTTPException\InternalServerErrorException
207          */
208         public static function searchContact($search, $mode, int $page = 1)
209         {
210                 Logger::info('Searching', ['search' => $search, 'mode' => $mode, 'page' => $page]);
211
212                 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
213                         return [];
214                 }
215
216                 // don't search if search term has less than 2 characters
217                 if (!$search || mb_strlen($search) < 2) {
218                         return [];
219                 }
220
221                 if (substr($search, 0, 1) === '@') {
222                         $search = substr($search, 1);
223                 }
224
225                 // check if searching in the local global contact table is enabled
226                 if (DI::config()->get('system', 'poco_local_search')) {
227                         $return = Contact::searchByName($search, $mode);
228                 } else {
229                         $p = $page > 1 ? 'p=' . $page : '';
230                         $curlResult = DI::httpRequest()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), ['accept_content' => 'application/json']);
231                         if ($curlResult->isSuccess()) {
232                                 $searchResult = json_decode($curlResult->getBody(), true);
233                                 if (!empty($searchResult['profiles'])) {
234                                         $return = $searchResult['profiles'];
235                                 }
236                         }
237                 }
238
239                 return $return ?? [];
240         }
241
242         /**
243          * Returns the global directory name, used in this node
244          *
245          * @return string
246          */
247         public static function getGlobalDirectory()
248         {
249                 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
250         }
251
252         /**
253          * Return the search path (either fulltext search or tag search)
254          *
255          * @param string $search
256          * @return string search path
257          */
258         public static function getSearchPath(string $search)
259         {
260                 if (substr($search, 0, 1) == '#') {
261                         return 'search?tag=' . urlencode(substr($search, 1));
262                 } else {
263                         return 'search?q=' . urlencode($search);
264                 }
265         }
266 }