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