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