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