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