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