]> git.mxchange.org Git - friendica.git/blob - src/Module/Search/Acl.php
2c0cc967c03f20cc0aad820712e6bf74d7483a8c
[friendica.git] / src / Module / Search / Acl.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\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\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Model\Contact;
33 use Friendica\Model\Item;
34 use Friendica\Network\HTTPException;
35 use Friendica\Util\Proxy as ProxyUtils;
36 use Friendica\Util\Strings;
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         public static function rawContent(array $parameters = [])
54         {
55                 if (!local_user()) {
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
61                 if ($type === self::TYPE_GLOBAL_CONTACT) {
62                         $o = self::globalContactSearch();
63                 } else {
64                         $o = self::regularContactSearch($type);
65                 }
66
67                 echo json_encode($o);
68                 exit;
69         }
70
71         private static function globalContactSearch()
72         {
73                 // autocomplete for global contact search (e.g. navbar search)
74                 $search = Strings::escapeTags(trim($_REQUEST['search']));
75                 $mode = $_REQUEST['smode'];
76                 $page = $_REQUEST['page'] ?? 1;
77
78                 $r = Search::searchGlobalContact($search, $mode, $page);
79
80                 $contacts = [];
81                 foreach ($r as $g) {
82                         if (empty($g['name'])) {
83                                 DI::logger()->warning('Wrong result item from Search::searchGlobalContact', ['$g' => $g, '$search' => $search, '$mode' => $mode, '$page' => $page]);
84                                 continue;
85                         }
86
87                         $contacts[] = [
88                                 'photo'   => ProxyUtils::proxifyUrl($g['photo'], false, ProxyUtils::SIZE_MICRO),
89                                 'name'    => htmlspecialchars($g['name']),
90                                 'nick'    => $g['addr'] ?: $g['url'],
91                                 'network' => $g['network'],
92                                 'link'    => $g['url'],
93                                 'forum'   => !empty($g['community']) ? 1 : 0,
94                         ];
95                 }
96
97                 $o = [
98                         'start' => ($page - 1) * 20,
99                         'count' => 1000,
100                         'items' => $contacts,
101                 ];
102
103                 return $o;
104         }
105
106         private static function regularContactSearch(string $type)
107         {
108                 $start   = $_REQUEST['start']        ?? 0;
109                 $count   = $_REQUEST['count']        ?? 100;
110                 $search  = $_REQUEST['search']       ?? '';
111                 $conv_id = $_REQUEST['conversation'] ?? null;
112
113                 // For use with jquery.textcomplete for private mail completion
114                 if (!empty($_REQUEST['query'])) {
115                         if (!$type) {
116                                 $type = self::TYPE_PRIVATE_MESSAGE;
117                         }
118                         $search = $_REQUEST['query'];
119                 }
120
121                 Logger::info('ACL {action} - {subaction}', ['module' => 'acl', 'action' => 'content', 'subaction' => 'search', 'search' => $search, 'type' => $type, 'conversation' => $conv_id]);
122
123                 $sql_extra = '';
124                 $sql_extra2 = '';
125
126                 if ($search != '') {
127                         $sql_extra = "AND `name` LIKE '%%" . DBA::escape($search) . "%%'";
128                         $sql_extra2 = "AND (`attag` LIKE '%%" . DBA::escape($search) . "%%' OR `name` LIKE '%%" . DBA::escape($search) . "%%' OR `nick` LIKE '%%" . DBA::escape($search) . "%%')";
129                 }
130
131                 // count groups and contacts
132                 $group_count = 0;
133                 if ($type == self::TYPE_MENTION_CONTACT_GROUP || $type == self::TYPE_MENTION_GROUP) {
134                         $r = q("SELECT COUNT(*) AS g FROM `group` WHERE NOT `deleted` AND `uid` = %d $sql_extra",
135                                 intval(local_user())
136                         );
137                         $group_count = (int) $r[0]['g'];
138                 }
139
140                 $sql_extra2 .= ' ' . Widget::unavailableNetworks();
141
142                 $contact_count = 0;
143                 switch ($type) {
144                         case self::TYPE_MENTION_CONTACT_GROUP:
145                         case self::TYPE_MENTION_CONTACT:
146                                 // autocomplete for editor mentions
147                                 $r = q("SELECT COUNT(*) AS c FROM `contact`
148                                         WHERE `uid` = %d AND NOT `self` AND NOT `deleted`
149                                         AND NOT `blocked` AND NOT `pending` AND NOT `archive`
150                                         AND `notify` != '' $sql_extra2",
151                                         intval(local_user())
152                                 );
153                                 $contact_count = (int) $r[0]['c'];
154                                 break;
155
156                         case self::TYPE_MENTION_FORUM:
157                                 // autocomplete for editor mentions of forums
158                                 $r = q("SELECT COUNT(*) AS c FROM `contact`
159                                         WHERE `uid` = %d AND NOT `self` AND NOT `deleted`
160                                         AND NOT `blocked` AND NOT `pending` AND NOT `archive`
161                                         AND (`forum` OR `prv`)
162                                         AND `notify` != '' $sql_extra2",
163                                         intval(local_user())
164                                 );
165                                 $contact_count = (int) $r[0]['c'];
166                                 break;
167
168                         case self::TYPE_PRIVATE_MESSAGE:
169                                 // autocomplete for Private Messages
170                                 $r = q("SELECT COUNT(*) AS c FROM `contact`
171                                         WHERE `uid` = %d AND NOT `self` AND NOT `deleted`
172                                         AND NOT `blocked` AND NOT `pending` AND NOT `archive`
173                                         AND `network` IN ('%s', '%s', '%s') $sql_extra2",
174                                         intval(local_user()),
175                                         DBA::escape(Protocol::ACTIVITYPUB),
176                                         DBA::escape(Protocol::DFRN),
177                                         DBA::escape(Protocol::DIASPORA)
178                                 );
179                                 $contact_count = (int) $r[0]['c'];
180                                 break;
181
182                         case self::TYPE_ANY_CONTACT:
183                         default:
184                                 // autocomplete for Contacts
185                                 $r = q("SELECT COUNT(*) AS c FROM `contact`
186                                         WHERE `uid` = %d AND NOT `self`
187                                         AND NOT `pending` AND NOT `deleted` $sql_extra2",
188                                         intval(local_user())
189                                 );
190                                 $contact_count = (int) $r[0]['c'];
191                                 break;
192                 }
193
194                 $tot = $group_count + $contact_count;
195
196                 $groups = [];
197                 $contacts = [];
198
199                 if ($type == self::TYPE_MENTION_CONTACT_GROUP || $type == self::TYPE_MENTION_GROUP) {
200                         /// @todo We should cache this query.
201                         // This can be done when we can delete cache entries via wildcard
202                         $r = q("SELECT `group`.`id`, `group`.`name`, GROUP_CONCAT(DISTINCT `group_member`.`contact-id` SEPARATOR ',') AS uids
203                                 FROM `group`
204                                 INNER JOIN `group_member` ON `group_member`.`gid`=`group`.`id`
205                                 WHERE NOT `group`.`deleted` AND `group`.`uid` = %d
206                                         $sql_extra
207                                 GROUP BY `group`.`name`, `group`.`id`
208                                 ORDER BY `group`.`name`
209                                 LIMIT %d, %d",
210                                 intval(local_user()),
211                                 intval($start),
212                                 intval($count)
213                         );
214
215                         foreach ($r as $g) {
216                                 $groups[] = [
217                                         'type'  => 'g',
218                                         'photo' => 'images/twopeople.png',
219                                         'name'  => htmlspecialchars($g['name']),
220                                         'id'    => intval($g['id']),
221                                         'uids'  => array_map('intval', explode(',', $g['uids'])),
222                                         'link'  => '',
223                                         'forum' => '0'
224                                 ];
225                         }
226                         if ((count($groups) > 0) && ($search == '')) {
227                                 $groups[] = ['separator' => true];
228                         }
229                 }
230
231                 $r = [];
232                 switch ($type) {
233                         case self::TYPE_MENTION_CONTACT_GROUP:
234                                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv`, (`prv` OR `forum`) AS `frm` FROM `contact`
235                                         WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
236                                         AND NOT (`network` IN ('%s', '%s'))
237                                         $sql_extra2
238                                         ORDER BY `name`",
239                                         intval(local_user()),
240                                         DBA::escape(Protocol::OSTATUS),
241                                         DBA::escape(Protocol::STATUSNET)
242                                 );
243                                 break;
244
245                         case self::TYPE_MENTION_CONTACT:
246                                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
247                                         WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
248                                         AND NOT (`network` IN ('%s'))
249                                         $sql_extra2
250                                         ORDER BY `name`",
251                                         intval(local_user()),
252                                         DBA::escape(Protocol::STATUSNET)
253                                 );
254                                 break;
255
256                         case self::TYPE_MENTION_FORUM:
257                                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
258                                         WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
259                                         AND NOT (`network` IN ('%s'))
260                                         AND (`forum` OR `prv`)
261                                         $sql_extra2
262                                         ORDER BY `name`",
263                                         intval(local_user()),
264                                         DBA::escape(Protocol::STATUSNET)
265                                 );
266                                 break;
267
268                         case self::TYPE_PRIVATE_MESSAGE:
269                                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr` FROM `contact`
270                                         WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive`
271                                         AND `network` IN ('%s', '%s', '%s')
272                                         $sql_extra2
273                                         ORDER BY `name`",
274                                         intval(local_user()),
275                                         DBA::escape(Protocol::ACTIVITYPUB),
276                                         DBA::escape(Protocol::DFRN),
277                                         DBA::escape(Protocol::DIASPORA)
278                                 );
279                                 break;
280
281                         case self::TYPE_ANY_CONTACT:
282                         default:
283                                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
284                                         WHERE `uid` = %d AND NOT `deleted` AND NOT `pending` AND NOT `archive`
285                                         $sql_extra2
286                                         ORDER BY `name`",
287                                         intval(local_user())
288                                 );
289                                 break;
290                 }
291
292                 if (DBA::isResult($r)) {
293                         $forums = [];
294                         foreach ($r as $g) {
295                                 $entry = [
296                                         'type'    => 'c',
297                                         'photo'   => Contact::getMicro($g),
298                                         'name'    => htmlspecialchars($g['name']),
299                                         'id'      => intval($g['id']),
300                                         'network' => $g['network'],
301                                         'link'    => $g['url'],
302                                         'nick'    => htmlentities(($g['attag'] ?? '') ?: $g['nick']),
303                                         'addr'    => htmlentities(($g['addr'] ?? '') ?: $g['url']),
304                                         'forum'   => !empty($g['forum']) || !empty($g['prv']) ? 1 : 0,
305                                 ];
306                                 if ($entry['forum']) {
307                                         $forums[] = $entry;
308                                 } else {
309                                         $contacts[] = $entry;
310                                 }
311                         }
312                         if (count($forums) > 0) {
313                                 if ($search == '') {
314                                         $forums[] = ['separator' => true];
315                                 }
316                                 $contacts = array_merge($forums, $contacts);
317                         }
318                 }
319
320                 $items = array_merge($groups, $contacts);
321
322                 if ($conv_id) {
323                         // In multi threaded posts the conv_id is not the parent of the whole thread
324                         $parent_item = Item::selectFirst(['parent'], ['id' => $conv_id]);
325                         if (DBA::isResult($parent_item)) {
326                                 $conv_id = $parent_item['parent'];
327                         }
328
329                         /*
330                          * if $conv_id is set, get unknown contacts in thread
331                          * but first get known contacts url to filter them out
332                          */
333                         $known_contacts = array_map(function ($i) {
334                                 return $i['link'];
335                         }, $contacts);
336
337                         $unknown_contacts = [];
338
339                         $condition = ["`parent` = ?", $conv_id];
340                         $params = ['order' => ['author-name' => true]];
341                         $authors = Item::selectForUser(local_user(), ['author-link'], $condition, $params);
342                         $item_authors = [];
343                         while ($author = Item::fetch($authors)) {
344                                 $item_authors[$author['author-link']] = $author['author-link'];
345                         }
346                         DBA::close($authors);
347
348                         foreach ($item_authors as $author) {
349                                 if (in_array($author, $known_contacts)) {
350                                         continue;
351                                 }
352
353                                 $contact = Contact::getByURL($author, false, ['micro', 'name', 'id', 'network', 'nick', 'addr', 'url', 'forum']);
354
355                                 if (count($contact) > 0) {
356                                         $unknown_contacts[] = [
357                                                 'type'    => 'c',
358                                                 'photo'   => Contact::getMicro($contact),
359                                                 'name'    => htmlspecialchars($contact['name']),
360                                                 'id'      => intval($contact['cid']),
361                                                 'network' => $contact['network'],
362                                                 'link'    => $contact['url'],
363                                                 'nick'    => htmlentities(($contact['nick'] ?? '') ?: $contact['addr']),
364                                                 'addr'    => htmlentities(($contact['addr'] ?? '') ?: $contact['url']),
365                                                 'forum'   => $contact['forum']
366                                         ];
367                                 }
368                         }
369
370                         $items = array_merge($items, $unknown_contacts);
371                         $tot += count($unknown_contacts);
372                 }
373
374                 $results = [
375                         'tot'      => $tot,
376                         'start'    => $start,
377                         'count'    => $count,
378                         'groups'   => $groups,
379                         'contacts' => $contacts,
380                         'items'    => $items,
381                         'type'     => $type,
382                         'search'   => $search,
383                 ];
384
385                 Hook::callAll('acl_lookup_end', $results);
386
387                 $o = [
388                         'tot'   => $results['tot'],
389                         'start' => $results['start'],
390                         'count' => $results['count'],
391                         'items' => $results['items'],
392                 ];
393
394                 return $o;
395         }
396 }