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