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