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