]> git.mxchange.org Git - friendica.git/blob - src/Module/Search/Acl.php
07cc9cdac5516865492e2d1db4a7e1ebc17efec4
[friendica.git] / src / Module / Search / Acl.php
1 <?php
2
3 namespace Friendica\Module\Search;
4
5 use Friendica\BaseModule;
6 use Friendica\Content\Widget;
7 use Friendica\Core\Config;
8 use Friendica\Core\Hook;
9 use Friendica\Core\L10n;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Core\Session;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Model\Item;
17 use Friendica\Network\HTTPException;
18 use Friendica\Util\Network;
19 use Friendica\Util\Proxy as ProxyUtils;
20 use Friendica\Util\Strings;
21
22 /**
23  * ACL selector json backend
24  *
25  * @package Friendica\Module\Search
26  */
27 class Acl extends BaseModule
28 {
29         public static function rawContent()
30         {
31                 if (!local_user()) {
32                         throw new HTTPException\UnauthorizedException(L10n::t('You must be logged in to use this module.'));
33                 }
34
35                 $start   = $_REQUEST['start']        ?? 0;
36                 $count   = $_REQUEST['count']        ?? 100;
37                 $search  = $_REQUEST['search']       ?? '';
38                 $type    = $_REQUEST['type']         ?? '';
39                 $conv_id = $_REQUEST['conversation'] ?? null;
40
41                 // For use with jquery.textcomplete for private mail completion
42                 if (!empty($_REQUEST['query'])) {
43                         if (!$type) {
44                                 $type = 'm';
45                         }
46                         $search = $_REQUEST['query'];
47                 }
48
49                 Logger::info('ACL {action} - {subaction}', ['module' => 'acl', 'action' => 'content', 'subaction' => 'search', 'search' => $search, 'type' => $type, 'conversation' => $conv_id]);
50
51                 $sql_extra = '';
52                 $sql_extra2 = '';
53
54                 if ($search != '') {
55                         $sql_extra = "AND `name` LIKE '%%" . DBA::escape($search) . "%%'";
56                         $sql_extra2 = "AND (`attag` LIKE '%%" . DBA::escape($search) . "%%' OR `name` LIKE '%%" . DBA::escape($search) . "%%' OR `nick` LIKE '%%" . DBA::escape($search) . "%%')";
57                 }
58
59                 // count groups and contacts
60                 $group_count = 0;
61                 if ($type == '' || $type == 'g') {
62                         $r = q("SELECT COUNT(*) AS g FROM `group` WHERE NOT `deleted` AND `uid` = %d $sql_extra",
63                                 intval(local_user())
64                         );
65                         $group_count = (int) $r[0]['g'];
66                 }
67
68                 $sql_extra2 .= ' ' . Widget::unavailableNetworks();
69
70                 $contact_count = 0;
71                 if ($type == '' || $type == 'c') {
72                         // autocomplete for editor mentions
73                         $r = q("SELECT COUNT(*) AS c FROM `contact`
74                                 WHERE `uid` = %d AND NOT `self` AND NOT `deleted`
75                                 AND NOT `blocked` AND NOT `pending` AND NOT `archive`
76                                 AND `notify` != '' $sql_extra2",
77                                 intval(local_user())
78                         );
79                         $contact_count = (int) $r[0]['c'];
80                 } elseif ($type == 'f') {
81                         // autocomplete for editor mentions of forums
82                         $r = q("SELECT COUNT(*) AS c FROM `contact`
83                                 WHERE `uid` = %d AND NOT `self` AND NOT `deleted`
84                                 AND NOT `blocked` AND NOT `pending` AND NOT `archive`
85                                 AND (`forum` OR `prv`)
86                                 AND `notify` != '' $sql_extra2",
87                                 intval(local_user())
88                         );
89                         $contact_count = (int) $r[0]['c'];
90                 } elseif ($type == 'm') {
91                         // autocomplete for Private Messages
92                         $r = q("SELECT COUNT(*) AS c FROM `contact`
93                                 WHERE `uid` = %d AND NOT `self` AND NOT `deleted`
94                                 AND NOT `blocked` AND NOT `pending` AND NOT `archive`
95                                 AND `network` IN ('%s', '%s', '%s') $sql_extra2",
96                                 intval(local_user()),
97                                 DBA::escape(Protocol::ACTIVITYPUB),
98                                 DBA::escape(Protocol::DFRN),
99                                 DBA::escape(Protocol::DIASPORA)
100                         );
101                         $contact_count = (int) $r[0]['c'];
102                 } elseif ($type == 'a') {
103                         // autocomplete for Contacts
104                         $r = q("SELECT COUNT(*) AS c FROM `contact`
105                                 WHERE `uid` = %d AND NOT `self`
106                                 AND NOT `pending` AND NOT `deleted` $sql_extra2",
107                                 intval(local_user())
108                         );
109                         $contact_count = (int) $r[0]['c'];
110                 }
111
112                 $tot = $group_count + $contact_count;
113
114                 $groups = [];
115                 $contacts = [];
116
117                 if ($type == '' || $type == 'g') {
118                         /// @todo We should cache this query.
119                         // This can be done when we can delete cache entries via wildcard
120                         $r = q("SELECT `group`.`id`, `group`.`name`, GROUP_CONCAT(DISTINCT `group_member`.`contact-id` SEPARATOR ',') AS uids
121                                 FROM `group`
122                                 INNER JOIN `group_member` ON `group_member`.`gid`=`group`.`id`
123                                 WHERE NOT `group`.`deleted` AND `group`.`uid` = %d
124                                         $sql_extra
125                                 GROUP BY `group`.`name`, `group`.`id`
126                                 ORDER BY `group`.`name`
127                                 LIMIT %d, %d",
128                                 intval(local_user()),
129                                 intval($start),
130                                 intval($count)
131                         );
132
133                         foreach ($r as $g) {
134                                 $groups[] = [
135                                         'type'  => 'g',
136                                         'photo' => 'images/twopeople.png',
137                                         'name'  => htmlspecialchars($g['name']),
138                                         'id'    => intval($g['id']),
139                                         'uids'  => array_map('intval', explode(',', $g['uids'])),
140                                         'link'  => '',
141                                         'forum' => '0'
142                                 ];
143                         }
144                         if ((count($groups) > 0) && ($search == '')) {
145                                 $groups[] = ['separator' => true];
146                         }
147                 }
148
149                 $r = [];
150                 if ($type == '') {
151                         $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv`, (`prv` OR `forum`) AS `frm` FROM `contact`
152                                 WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
153                                 AND NOT (`network` IN ('%s', '%s'))
154                                 $sql_extra2
155                                 ORDER BY `name`",
156                                 intval(local_user()),
157                                 DBA::escape(Protocol::OSTATUS),
158                                 DBA::escape(Protocol::STATUSNET)
159                         );
160                 } elseif ($type == 'c') {
161                         $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
162                                 WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
163                                 AND NOT (`network` IN ('%s'))
164                                 $sql_extra2
165                                 ORDER BY `name`",
166                                 intval(local_user()),
167                                 DBA::escape(Protocol::STATUSNET)
168                         );
169                 } elseif ($type == 'f') {
170                         $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
171                                 WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
172                                 AND NOT (`network` IN ('%s'))
173                                 AND (`forum` OR `prv`)
174                                 $sql_extra2
175                                 ORDER BY `name`",
176                                 intval(local_user()),
177                                 DBA::escape(Protocol::STATUSNET)
178                         );
179                 } elseif ($type == 'm') {
180                         $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr` FROM `contact`
181                                 WHERE `uid` = %d AND NOT `self` AND NOT `deleted` AND NOT `blocked` AND NOT `pending` AND NOT `archive`
182                                 AND `network` IN ('%s', '%s', '%s')
183                                 $sql_extra2
184                                 ORDER BY `name`",
185                                 intval(local_user()),
186                                 DBA::escape(Protocol::ACTIVITYPUB),
187                                 DBA::escape(Protocol::DFRN),
188                                 DBA::escape(Protocol::DIASPORA)
189                         );
190                 } elseif ($type == 'a') {
191                         $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
192                                 WHERE `uid` = %d AND NOT `deleted` AND NOT `pending` AND NOT `archive`
193                                 $sql_extra2
194                                 ORDER BY `name`",
195                                 intval(local_user())
196                         );
197                 } elseif ($type == 'x') {
198                         // autocomplete for global contact search (e.g. navbar search)
199                         $search = Strings::escapeTags(trim($_REQUEST['search']));
200                         $mode = $_REQUEST['smode'];
201                         $page = $_REQUEST['page'] ?? 1;
202
203                         $r = self::contactAutocomplete($search, $mode, $page);
204
205                         $contacts = [];
206                         foreach ($r as $g) {
207                                 $contacts[] = [
208                                         'photo'   => ProxyUtils::proxifyUrl($g['photo'], false, ProxyUtils::SIZE_MICRO),
209                                         'name'    => htmlspecialchars($g['name']),
210                                         'nick'    => $g['addr'] ?: $g['url'],
211                                         'network' => $g['network'],
212                                         'link'    => $g['url'],
213                                         'forum'   => !empty($g['community']) ? 1 : 0,
214                                 ];
215                         }
216                         $o = [
217                                 'start' => $start,
218                                 'count' => $count,
219                                 'items' => $contacts,
220                         ];
221                         echo json_encode($o);
222                         exit;
223                 }
224
225                 if (DBA::isResult($r)) {
226                         $forums = [];
227                         foreach ($r as $g) {
228                                 $entry = [
229                                         'type'    => 'c',
230                                         'photo'   => ProxyUtils::proxifyUrl($g['micro'], false, ProxyUtils::SIZE_MICRO),
231                                         'name'    => htmlspecialchars($g['name']),
232                                         'id'      => intval($g['id']),
233                                         'network' => $g['network'],
234                                         'link'    => $g['url'],
235                                         'nick'    => htmlentities(defaults($g, 'attag', $g['nick'])),
236                                         'addr'    => htmlentities(defaults($g, 'addr', $g['url'])),
237                                         'forum'   => !empty($g['forum']) || !empty($g['prv']) ? 1 : 0,
238                                 ];
239                                 if ($entry['forum']) {
240                                         $forums[] = $entry;
241                                 } else {
242                                         $contacts[] = $entry;
243                                 }
244                         }
245                         if (count($forums) > 0) {
246                                 if ($search == '') {
247                                         $forums[] = ['separator' => true];
248                                 }
249                                 $contacts = array_merge($forums, $contacts);
250                         }
251                 }
252
253                 $items = array_merge($groups, $contacts);
254
255                 if ($conv_id) {
256                         // In multi threaded posts the conv_id is not the parent of the whole thread
257                         $parent_item = Item::selectFirst(['parent'], ['id' => $conv_id]);
258                         if (DBA::isResult($parent_item)) {
259                                 $conv_id = $parent_item['parent'];
260                         }
261
262                         /*
263                          * if $conv_id is set, get unknown contacts in thread
264                          * but first get known contacts url to filter them out
265                          */
266                         $known_contacts = array_map(function ($i) {
267                                 return $i['link'];
268                         }, $contacts);
269
270                         $unknown_contacts = [];
271
272                         $condition = ["`parent` = ?", $conv_id];
273                         $params = ['order' => ['author-name' => true]];
274                         $authors = Item::selectForUser(local_user(), ['author-link'], $condition, $params);
275                         $item_authors = [];
276                         while ($author = Item::fetch($authors)) {
277                                 $item_authors[$author['author-link']] = $author['author-link'];
278                         }
279                         DBA::close($authors);
280
281                         foreach ($item_authors as $author) {
282                                 if (in_array($author, $known_contacts)) {
283                                         continue;
284                                 }
285
286                                 $contact = Contact::getDetailsByURL($author);
287
288                                 if (count($contact) > 0) {
289                                         $unknown_contacts[] = [
290                                                 'type'    => 'c',
291                                                 'photo'   => ProxyUtils::proxifyUrl($contact['micro'], false, ProxyUtils::SIZE_MICRO),
292                                                 'name'    => htmlspecialchars($contact['name']),
293                                                 'id'      => intval($contact['cid']),
294                                                 'network' => $contact['network'],
295                                                 'link'    => $contact['url'],
296                                                 'nick'    => htmlentities(defaults($contact, 'nick', $contact['addr'])),
297                                                 'addr'    => htmlentities(defaults($contact, 'addr', $contact['url'])),
298                                                 'forum'   => $contact['forum']
299                                         ];
300                                 }
301                         }
302
303                         $items = array_merge($items, $unknown_contacts);
304                         $tot += count($unknown_contacts);
305                 }
306
307                 $results = [
308                         'tot'      => $tot,
309                         'start'    => $start,
310                         'count'    => $count,
311                         'groups'   => $groups,
312                         'contacts' => $contacts,
313                         'items'    => $items,
314                         'type'     => $type,
315                         'search'   => $search,
316                 ];
317
318                 Hook::callAll('acl_lookup_end', $results);
319
320                 $o = [
321                         'tot'   => $results['tot'],
322                         'start' => $results['start'],
323                         'count' => $results['count'],
324                         'items' => $results['items'],
325                 ];
326
327                 echo json_encode($o);
328                 exit;
329         }
330
331
332         /**
333          * Searching for global contacts for autocompletion
334          *
335          * @brief Searching for global contacts for autocompletion
336          * @param string $search Name or part of a name or nick
337          * @param string $mode   Search mode (e.g. "community")
338          * @param int    $page   Page number (starts at 1)
339          * @return array with the search results
340          * @throws HTTPException\InternalServerErrorException
341          */
342         private static function contactAutocomplete($search, $mode, int $page = 1)
343         {
344                 if (Config::get('system', 'block_public') && !Session::isAuthenticated()) {
345                         return [];
346                 }
347
348                 // don't search if search term has less than 2 characters
349                 if (!$search || mb_strlen($search) < 2) {
350                         return [];
351                 }
352
353                 if (substr($search, 0, 1) === '@') {
354                         $search = substr($search, 1);
355                 }
356
357                 // check if searching in the local global contact table is enabled
358                 if (Config::get('system', 'poco_local_search')) {
359                         $return = GContact::searchByName($search, $mode);
360                 } else {
361                         $p = $page > 1 ? 'p=' . $page : '';
362
363                         $curlResult = Network::curl(get_server() . '/lsearch?' . $p . '&search=' . urlencode($search));
364                         if ($curlResult->isSuccess()) {
365                                 $lsearch = json_decode($curlResult->getBody(), true);
366                                 if (!empty($lsearch['results'])) {
367                                         $return = $lsearch['results'];
368                                 }
369                         }
370                 }
371
372                 return $return ?? [];
373         }
374 }