]> git.mxchange.org Git - friendica.git/blob - src/Module/Search/Acl.php
Merge pull request #12589 from MrPetovan/bug/warnings
[friendica.git] / src / Module / Search / Acl.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, 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\Module\Search;
23
24 use Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Content\Widget;
27 use Friendica\Core\Hook;
28 use Friendica\Core\L10n;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Search;
31 use Friendica\Core\Session\Capability\IHandleUserSessions;
32 use Friendica\Core\System;
33 use Friendica\Database\Database;
34 use Friendica\Database\DBA;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Post;
37 use Friendica\Module\Response;
38 use Friendica\Network\HTTPException;
39 use Friendica\Util\Profiler;
40 use Psr\Log\LoggerInterface;
41
42 /**
43  * ACL selector json backend
44  *
45  * @package Friendica\Module\Search
46  */
47 class Acl extends BaseModule
48 {
49         const TYPE_GLOBAL_CONTACT        = 'x';
50         const TYPE_MENTION_CONTACT       = 'c';
51         const TYPE_MENTION_GROUP         = 'g';
52         const TYPE_MENTION_CONTACT_GROUP = '';
53         const TYPE_MENTION_FORUM         = 'f';
54         const TYPE_PRIVATE_MESSAGE       = 'm';
55         const TYPE_ANY_CONTACT           = 'a';
56
57         /** @var IHandleUserSessions */
58         private $session;
59         /** @var Database */
60         private $database;
61
62         public function __construct(Database $database, IHandleUserSessions $session, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, Response $response, array $server, array $parameters = [])
63         {
64                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
65
66                 $this->session  = $session;
67                 $this->database = $database;
68         }
69
70         protected function rawContent(array $request = [])
71         {
72                 if (!$this->session->getLocalUserId()) {
73                         throw new HTTPException\UnauthorizedException($this->t('You must be logged in to use this module.'));
74                 }
75
76                 $type = $request['type'] ?? self::TYPE_MENTION_CONTACT_GROUP;
77                 if ($type === self::TYPE_GLOBAL_CONTACT) {
78                         $o = $this->globalContactSearch($request);
79                 } else {
80                         $o = $this->regularContactSearch($request, $type);
81                 }
82
83                 System::jsonExit($o);
84         }
85
86         private function globalContactSearch(array $request): array
87         {
88                 // autocomplete for global contact search (e.g. navbar search)
89                 $search = trim($request['search']);
90                 $mode   = $request['smode'];
91                 $page   = $request['page'] ?? 1;
92
93                 $result = Search::searchContact($search, $mode, $page);
94
95                 $contacts = [];
96                 foreach ($result as $contact) {
97                         $contacts[] = [
98                                 'photo'   => Contact::getMicro($contact, true),
99                                 'name'    => htmlspecialchars($contact['name']),
100                                 'nick'    => $contact['addr'] ?: $contact['url'],
101                                 'network' => $contact['network'],
102                                 'link'    => $contact['url'],
103                                 'forum'   => $contact['contact-type'] == Contact::TYPE_COMMUNITY,
104                         ];
105                 }
106
107                 return [
108                         'start' => ($page - 1) * 20,
109                         'count' => 1000,
110                         'items' => $contacts,
111                 ];
112         }
113
114         private function regularContactSearch(array $request, string $type): array
115         {
116                 $start   = $request['start'] ?? 0;
117                 $count   = $request['count'] ?? 100;
118                 $search  = $request['search'] ?? '';
119                 $conv_id = $request['conversation'] ?? null;
120
121                 // For use with jquery.textcomplete for private mail completion
122                 if (!empty($request['query'])) {
123                         if (!$type) {
124                                 $type = self::TYPE_PRIVATE_MESSAGE;
125                         }
126                         $search = $request['query'];
127                 }
128
129                 $this->logger->info('ACL {action} - {subaction} - start', ['module' => 'acl', 'action' => 'content', 'subaction' => 'search', 'search' => $search, 'type' => $type, 'conversation' => $conv_id]);
130
131                 $sql_extra       = '';
132                 $condition       = ["`uid` = ? AND NOT `deleted` AND NOT `pending` AND NOT `archive`", $this->session->getLocalUserId()];
133                 $condition_group = ["`uid` = ? AND NOT `deleted`", $this->session->getLocalUserId()];
134
135                 if ($search != '') {
136                         $sql_extra       = "AND `name` LIKE '%%" . $this->database->escape($search) . "%%'";
137                         $condition       = DBA::mergeConditions($condition, ["(`attag` LIKE ? OR `name` LIKE ? OR `nick` LIKE ?)",
138                                                                              '%' . $search . '%', '%' . $search . '%', '%' . $search . '%']);
139                         $condition_group = DBA::mergeConditions($condition_group, ["`name` LIKE ?", '%' . $search . '%']);
140                 }
141
142                 // count groups and contacts
143                 $group_count = 0;
144                 if ($type == self::TYPE_MENTION_CONTACT_GROUP || $type == self::TYPE_MENTION_GROUP) {
145                         $group_count = $this->database->count('group', $condition_group);
146                 }
147
148                 $networks  = Widget::unavailableNetworks();
149                 $condition = DBA::mergeConditions($condition, array_merge(["NOT `network` IN (" . substr(str_repeat("?, ", count($networks)), 0, -2) . ")"], $networks));
150
151                 switch ($type) {
152                         case self::TYPE_MENTION_CONTACT_GROUP:
153                                 $condition = DBA::mergeConditions($condition,
154                                         ["NOT `self` AND NOT `blocked` AND `notify` != ? AND `network` != ?", '', Protocol::OSTATUS
155                                         ]);
156                                 break;
157
158                         case self::TYPE_MENTION_CONTACT:
159                                 $condition = DBA::mergeConditions($condition,
160                                         ["NOT `self` AND NOT `blocked` AND `notify` != ?", ''
161                                         ]);
162                                 break;
163
164                         case self::TYPE_MENTION_FORUM:
165                                 $condition = DBA::mergeConditions($condition,
166                                         ["NOT `self` AND NOT `blocked` AND `notify` != ? AND `contact-type` = ?", '', Contact::TYPE_COMMUNITY
167                                         ]);
168                                 break;
169
170                         case self::TYPE_PRIVATE_MESSAGE:
171                                 $condition = DBA::mergeConditions($condition,
172                                         ["NOT `self` AND NOT `blocked` AND `notify` != ? AND `network` IN (?, ?, ?)", '', Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA
173                                         ]);
174                                 break;
175                 }
176
177                 $contact_count = $this->database->count('contact', $condition);
178
179                 $resultTotal = $group_count + $contact_count;
180
181                 $resultGroups   = [];
182                 $resultContacts = [];
183
184                 if ($type == self::TYPE_MENTION_CONTACT_GROUP || $type == self::TYPE_MENTION_GROUP) {
185                         /// @todo We should cache this query.
186                         // This can be done when we can delete cache entries via wildcard
187                         $groups = $this->database->toArray($this->database->p("SELECT `group`.`id`, `group`.`name`, GROUP_CONCAT(DISTINCT `group_member`.`contact-id` SEPARATOR ',') AS uids
188                                 FROM `group`
189                                 INNER JOIN `group_member` ON `group_member`.`gid`=`group`.`id`
190                                 WHERE NOT `group`.`deleted` AND `group`.`uid` = ?
191                                         $sql_extra
192                                 GROUP BY `group`.`name`, `group`.`id`
193                                 ORDER BY `group`.`name`
194                                 LIMIT ?, ?",
195                                 $this->session->getLocalUserId(),
196                                 $start,
197                                 $count
198                         ));
199
200                         foreach ($groups as $group) {
201                                 $resultGroups[] = [
202                                         'type'  => 'g',
203                                         'photo' => 'images/twopeople.png',
204                                         'name'  => htmlspecialchars($group['name']),
205                                         'id'    => intval($group['id']),
206                                         'uids'  => array_map('intval', explode(',', $group['uids'])),
207                                         'link'  => '',
208                                         'forum' => '0'
209                                 ];
210                         }
211                         if ((count($resultGroups) > 0) && ($search == '')) {
212                                 $resultGroups[] = ['separator' => true];
213                         }
214                 }
215
216                 $contacts = [];
217                 if ($type != self::TYPE_MENTION_GROUP) {
218                         $contacts = Contact::selectToArray([], $condition, ['order' => ['name']]);
219                 }
220
221                 $forums = [];
222                 foreach ($contacts as $contact) {
223                         $entry = [
224                                 'type'    => 'c',
225                                 'photo'   => Contact::getMicro($contact, true),
226                                 'name'    => htmlspecialchars($contact['name']),
227                                 'id'      => intval($contact['id']),
228                                 'network' => $contact['network'],
229                                 'link'    => $contact['url'],
230                                 'nick'    => htmlentities(($contact['attag'] ?? '') ?: $contact['nick']),
231                                 'addr'    => htmlentities(($contact['addr'] ?? '') ?: $contact['url']),
232                                 'forum'   => $contact['contact-type'] == Contact::TYPE_COMMUNITY,
233                         ];
234                         if ($entry['forum']) {
235                                 $forums[] = $entry;
236                         } else {
237                                 $resultContacts[] = $entry;
238                         }
239                 }
240
241                 if ($forums) {
242                         if ($search == '') {
243                                 $forums[] = ['separator' => true];
244                         }
245
246                         $resultContacts = array_merge($forums, $resultContacts);
247                 }
248
249                 $resultItems = array_merge($resultGroups, $resultContacts);
250
251                 if ($conv_id) {
252                         // In multithreaded posts the conv_id is not the parent of the whole thread
253                         $parent_item = Post::selectFirst(['parent'], ['id' => $conv_id]);
254                         if ($parent_item) {
255                                 $conv_id = $parent_item['parent'];
256                         }
257
258                         /*
259                          * if $conv_id is set, get unknown contacts in thread
260                          * but first get known contacts url to filter them out
261                          */
262                         $known_contacts = array_column($resultContacts, 'link');
263
264                         $unknown_contacts = [];
265
266                         $condition    = ["`parent` = ?", $conv_id];
267                         $params       = ['order' => ['author-name' => true]];
268                         $authors      = Post::selectForUser($this->session->getLocalUserId(), ['author-link'], $condition, $params);
269                         $item_authors = [];
270                         while ($author = Post::fetch($authors)) {
271                                 $item_authors[$author['author-link']] = $author['author-link'];
272                         }
273
274                         $this->database->close($authors);
275
276                         foreach (array_diff($item_authors, $known_contacts) as $author) {
277                                 $contact = Contact::getByURL($author, false, ['micro', 'name', 'id', 'network', 'nick', 'addr', 'url', 'forum', 'avatar']);
278                                 if ($contact) {
279                                         $unknown_contacts[] = [
280                                                 'type'    => 'c',
281                                                 'photo'   => Contact::getMicro($contact, true),
282                                                 'name'    => htmlspecialchars($contact['name']),
283                                                 'id'      => intval($contact['id']),
284                                                 'network' => $contact['network'],
285                                                 'link'    => $contact['url'],
286                                                 'nick'    => htmlentities(($contact['nick'] ?? '') ?: $contact['addr']),
287                                                 'addr'    => htmlentities(($contact['addr'] ?? '') ?: $contact['url']),
288                                                 'forum'   => $contact['forum']
289                                         ];
290                                 }
291                         }
292
293                         $resultItems = array_merge($resultItems, $unknown_contacts);
294                         $resultTotal += count($unknown_contacts);
295                 }
296
297                 $results = [
298                         'tot'      => $resultTotal,
299                         'start'    => $start,
300                         'count'    => $count,
301                         'groups'   => $resultGroups,
302                         'contacts' => $resultContacts,
303                         'items'    => $resultItems,
304                         'type'     => $type,
305                         'search'   => $search,
306                 ];
307
308                 Hook::callAll('acl_lookup_end', $results);
309
310                 $o = [
311                         'tot'   => $results['tot'],
312                         'start' => $results['start'],
313                         'count' => $results['count'],
314                         'items' => $results['items'],
315                 ];
316
317                 $this->logger->info('ACL {action} - {subaction} - done', ['module' => 'acl', 'action' => 'content', 'subaction' => 'search', 'search' => $search, 'type' => $type, 'conversation' => $conv_id]);
318                 return $o;
319         }
320 }