]> git.mxchange.org Git - friendica.git/blob - src/Core/Search.php
Merge remote-tracking branch 'upstream/develop' into personal-copy
[friendica.git] / src / Core / Search.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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\Database\DBA;
25 use Friendica\DI;
26 use Friendica\Model\Contact;
27 use Friendica\Model\GContact;
28 use Friendica\Network\HTTPException;
29 use Friendica\Object\Search\ContactResult;
30 use Friendica\Object\Search\ResultList;
31 use Friendica\Util\Network;
32 use Friendica\Util\Strings;
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($user)
59         {
60                 $emptyResultList = new ResultList(1, 0, 1);
61
62                 if ((filter_var($user, FILTER_VALIDATE_EMAIL) && Network::isEmailDomainValid($user)) ||
63                     (substr(Strings::normaliseLink($user), 0, 7) == "http://")) {
64
65                         $user_data = Contact::getByURL($user);
66                         if (empty($user_data)) {
67                                 return $emptyResultList;
68                         }
69
70                         if (!in_array($user_data["network"], Protocol::FEDERATED)) {
71                                 return $emptyResultList;
72                         }
73
74                         $contactDetails = Contact::getByURLForUser($user_data['url'] ?? '', local_user());
75
76                         $result = new ContactResult(
77                                 $user_data['name'] ?? '',
78                                 $user_data['addr'] ?? '',
79                                 ($contactDetails['addr'] ?? '') ?: ($user_data['url'] ?? ''),
80                                 $user_data['url'] ?? '',
81                                 $user_data['photo'] ?? '',
82                                 $user_data['network'] ?? '',
83                                 $contactDetails['id'] ?? 0,
84                                 $user_data['id'] ?? 0,
85                                 $user_data['tags'] ?? ''
86                         );
87
88                         return new ResultList(1, 1, 1, [$result]);
89                 } else {
90                         return $emptyResultList;
91                 }
92         }
93
94         /**
95          * Search in the global directory for occurrences of the search string
96          *
97          * @see https://github.com/friendica/friendica-directory/blob/stable/docs/Protocol.md#search
98          *
99          * @param string $search
100          * @param int    $type specific type of searching
101          * @param int    $page
102          *
103          * @return ResultList
104          * @throws HTTPException\InternalServerErrorException
105          */
106         public static function getContactsFromGlobalDirectory($search, $type = self::TYPE_ALL, $page = 1)
107         {
108                 $server = DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
109
110                 $searchUrl = $server . '/search';
111
112                 switch ($type) {
113                         case self::TYPE_FORUM:
114                                 $searchUrl .= '/forum';
115                                 break;
116                         case self::TYPE_PEOPLE:
117                                 $searchUrl .= '/people';
118                                 break;
119                 }
120                 $searchUrl .= '?q=' . urlencode($search);
121
122                 if ($page > 1) {
123                         $searchUrl .= '&page=' . $page;
124                 }
125
126                 $resultJson = DI::httpRequest()->fetch($searchUrl, false, 0, 'application/json');
127
128                 $results = json_decode($resultJson, true);
129
130                 $resultList = new ResultList(
131                         ($results['page']         ?? 0) ?: 1,
132                          $results['count']        ?? 0,
133                         ($results['itemsperpage'] ?? 0) ?: 30
134                 );
135
136                 $profiles = $results['profiles'] ?? [];
137
138                 foreach ($profiles as $profile) {
139                         $profile_url = $profile['url'] ?? '';
140                         $contactDetails = Contact::getByURLForUser($profile_url, local_user());
141
142                         $result = new ContactResult(
143                                 $profile['name'] ?? '',
144                                 $profile['addr'] ?? '',
145                                 ($contactDetails['addr'] ?? '') ?: $profile_url,
146                                 $profile_url,
147                                 $profile['photo'] ?? '',
148                                 Protocol::DFRN,
149                                 $contactDetails['cid'] ?? 0,
150                                 0,
151                                 $profile['tags'] ?? ''
152                         );
153
154                         $resultList->addResult($result);
155                 }
156
157                 return $resultList;
158         }
159
160         /**
161          * Search in the local database for occurrences of the search string
162          *
163          * @param string $search
164          * @param int    $type
165          * @param int    $start
166          * @param int    $itemPage
167          *
168          * @return ResultList
169          * @throws HTTPException\InternalServerErrorException
170          */
171         public static function getContactsFromLocalDirectory($search, $type = self::TYPE_ALL, $start = 0, $itemPage = 80)
172         {
173                 $config = DI::config();
174
175                 $diaspora = $config->get('system', 'diaspora_enabled') ? Protocol::DIASPORA : Protocol::DFRN;
176                 $ostatus  = !$config->get('system', 'ostatus_disabled') ? Protocol::OSTATUS : Protocol::DFRN;
177
178                 $wildcard = Strings::escapeHtml('%' . $search . '%');
179
180                 $count = DBA::count('gcontact', [
181                         'NOT `hide`
182                         AND `network` IN (?, ?, ?, ?)
183                         AND NOT `failed`
184                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
185                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
186                         AND `community` = ?',
187                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
188                         $wildcard, $wildcard, $wildcard,
189                         $wildcard, $wildcard, $wildcard,
190                         ($type === self::TYPE_FORUM),
191                 ]);
192
193                 $resultList = new ResultList($start, $itemPage, $count);
194
195                 if (empty($count)) {
196                         return $resultList;
197                 }
198
199                 $data = DBA::select('gcontact', ['nurl', 'name', 'addr', 'url', 'photo', 'network', 'keywords'], [
200                         'NOT `hide`
201                         AND `network` IN (?, ?, ?, ?)
202                         AND NOT `failed`
203                         AND (`url` LIKE ? OR `name` LIKE ? OR `location` LIKE ? 
204                                 OR `addr` LIKE ? OR `about` LIKE ? OR `keywords` LIKE ?)
205                         AND `community` = ?',
206                         Protocol::ACTIVITYPUB, Protocol::DFRN, $ostatus, $diaspora,
207                         $wildcard, $wildcard, $wildcard,
208                         $wildcard, $wildcard, $wildcard,
209                         ($type === self::TYPE_FORUM),
210                 ], [
211                         'group_by' => ['nurl', 'updated'],
212                         'limit'    => [$start, $itemPage],
213                         'order'    => ['updated' => 'DESC']
214                 ]);
215
216                 if (!DBA::isResult($data)) {
217                         return $resultList;
218                 }
219
220                 while ($row = DBA::fetch($data)) {
221                         $urlParts = parse_url($row["nurl"]);
222
223                         // Ignore results that look strange.
224                         // For historic reasons the gcontact table does contain some garbage.
225                         if (!empty($urlParts['query']) || !empty($urlParts['fragment'])) {
226                                 continue;
227                         }
228
229                         $contact = Contact::getByURLForUser($row["nurl"], local_user()) ?: $row;
230
231                         if ($contact["name"] == "") {
232                                 $contact["name"] = end(explode("/", $urlParts["path"]));
233                         }
234
235                         $result = new ContactResult(
236                                 $contact["name"],
237                                 $contact["addr"],
238                                 $contact["addr"],
239                                 $contact["url"],
240                                 $contact["photo"],
241                                 $contact["network"],
242                                 $contact["cid"] ?? 0,
243                                 $contact["zid"] ?? 0,
244                                 $contact["keywords"]
245                         );
246
247                         $resultList->addResult($result);
248                 }
249
250                 DBA::close($data);
251
252                 // Add found profiles from the global directory to the local directory
253                 Worker::add(PRIORITY_LOW, 'SearchDirectory', $search);
254
255                 return $resultList;
256         }
257
258         /**
259          * Searching for global contacts for autocompletion
260          *
261          * @param string $search Name or part of a name or nick
262          * @param string $mode   Search mode (e.g. "community")
263          * @param int    $page   Page number (starts at 1)
264          * @return array with the search results
265          * @throws HTTPException\InternalServerErrorException
266          */
267         public static function searchGlobalContact($search, $mode, int $page = 1)
268         {
269                 if (DI::config()->get('system', 'block_public') && !Session::isAuthenticated()) {
270                         return [];
271                 }
272
273                 // don't search if search term has less than 2 characters
274                 if (!$search || mb_strlen($search) < 2) {
275                         return [];
276                 }
277
278                 if (substr($search, 0, 1) === '@') {
279                         $search = substr($search, 1);
280                 }
281
282                 // check if searching in the local global contact table is enabled
283                 if (DI::config()->get('system', 'poco_local_search')) {
284                         $return = GContact::searchByName($search, $mode);
285                 } else {
286                         $p = $page > 1 ? 'p=' . $page : '';
287                         $curlResult = DI::httpRequest()->get(self::getGlobalDirectory() . '/search/people?' . $p . '&q=' . urlencode($search), false, ['accept_content' => 'application/json']);
288                         if ($curlResult->isSuccess()) {
289                                 $searchResult = json_decode($curlResult->getBody(), true);
290                                 if (!empty($searchResult['profiles'])) {
291                                         $return = $searchResult['profiles'];
292                                 }
293                         }
294                 }
295
296                 return $return ?? [];
297         }
298
299         /**
300          * Returns the global directory name, used in this node
301          *
302          * @return string
303          */
304         public static function getGlobalDirectory()
305         {
306                 return DI::config()->get('system', 'directory', self::DEFAULT_DIRECTORY);
307         }
308
309         /**
310          * Return the search path (either fulltext search or tag search)
311          *
312          * @param string $search
313          * @return string search path
314          */
315         public static function getSearchPath(string $search)
316         {
317                 if (substr($search, 0, 1) == '#') {
318                         return 'search?tag=' . urlencode(substr($search, 1));
319                 } else {
320                         return 'search?q=' . urlencode($search);
321                 }
322         }
323 }