]> git.mxchange.org Git - friendica.git/blob - src/Core/ACL.php
Remove duplicate profile_uid key in App->profile array
[friendica.git] / src / Core / ACL.php
1 <?php
2
3 /**
4  * @file src/Core/Acl.php
5  */
6
7 namespace Friendica\Core;
8
9 use Friendica\App\Page;
10 use Friendica\Database\DBA;
11 use Friendica\DI;
12 use Friendica\Model\Contact;
13 use Friendica\Model\Group;
14
15 /**
16  * Handle ACL management and display
17  *
18  * @author Hypolite Petovan <hypolite@mrpetovan.com>
19  */
20 class ACL
21 {
22         /**
23          * Returns a select input tag with all the contact of the local user
24          *
25          * @param string $selname     Name attribute of the select input tag
26          * @param string $selclass    Class attribute of the select input tag
27          * @param array  $options     Available options:
28          *                            - size: length of the select box
29          *                            - mutual_friends: Only used for the hook
30          *                            - single: Only used for the hook
31          *                            - exclude: Only used for the hook
32          * @param array  $preselected Contact ID that should be already selected
33          * @return string
34          * @throws \Exception
35          */
36         public static function getSuggestContactSelectHTML($selname, $selclass, array $options = [], array $preselected = [])
37         {
38                 $a = DI::app();
39
40                 $networks = null;
41
42                 $size = ($options['size'] ?? 0) ?: 4;
43                 $mutual = !empty($options['mutual_friends']);
44                 $single = !empty($options['single']) && empty($options['multiple']);
45                 $exclude = $options['exclude'] ?? false;
46
47                 switch (($options['networks'] ?? '') ?: Protocol::PHANTOM) {
48                         case 'DFRN_ONLY':
49                                 $networks = [Protocol::DFRN];
50                                 break;
51
52                         case 'PRIVATE':
53                                 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::MAIL, Protocol::DIASPORA];
54                                 break;
55
56                         case 'TWO_WAY':
57                                 if (!empty($a->user['prvnets'])) {
58                                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::MAIL, Protocol::DIASPORA];
59                                 } else {
60                                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::MAIL, Protocol::DIASPORA, Protocol::OSTATUS];
61                                 }
62                                 break;
63
64                         default: /// @TODO Maybe log this call?
65                                 break;
66                 }
67
68                 $x = ['options' => $options, 'size' => $size, 'single' => $single, 'mutual' => $mutual, 'exclude' => $exclude, 'networks' => $networks];
69
70                 Hook::callAll('contact_select_options', $x);
71
72                 $o = '';
73
74                 $sql_extra = '';
75
76                 if (!empty($x['mutual'])) {
77                         $sql_extra .= sprintf(" AND `rel` = %d ", intval(Contact::FRIEND));
78                 }
79
80                 if (!empty($x['exclude'])) {
81                         $sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude']));
82                 }
83
84                 if (!empty($x['networks'])) {
85                         /// @TODO rewrite to foreach()
86                         array_walk($x['networks'], function (&$value) {
87                                 $value = "'" . DBA::escape($value) . "'";
88                         });
89                         $str_nets = implode(',', $x['networks']);
90                         $sql_extra .= " AND `network` IN ( $str_nets ) ";
91                 }
92
93                 $tabindex = (!empty($options['tabindex']) ? 'tabindex="' . $options["tabindex"] . '"' : '');
94
95                 if (!empty($x['single'])) {
96                         $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"" . $x['size'] . "\" $tabindex >\r\n";
97                 } else {
98                         $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"" . $x['size'] . "$\" $tabindex >\r\n";
99                 }
100
101                 $stmt = DBA::p("SELECT `id`, `name`, `url`, `network` FROM `contact`
102                         WHERE `uid` = ? AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND NOT `deleted` AND `notify` != ''
103                         $sql_extra
104                         ORDER BY `name` ASC ", intval(local_user())
105                 );
106
107                 $contacts = DBA::toArray($stmt);
108
109                 $arr = ['contact' => $contacts, 'entry' => $o];
110
111                 // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
112                 Hook::callAll(DI::module()->getName() . '_pre_' . $selname, $arr);
113
114                 if (DBA::isResult($contacts)) {
115                         foreach ($contacts as $contact) {
116                                 if (in_array($contact['id'], $preselected)) {
117                                         $selected = ' selected="selected" ';
118                                 } else {
119                                         $selected = '';
120                                 }
121
122                                 $trimmed = mb_substr($contact['name'], 0, 20);
123
124                                 $o .= "<option value=\"{$contact['id']}\" $selected title=\"{$contact['name']}|{$contact['url']}\" >$trimmed</option>\r\n";
125                         }
126                 }
127
128                 $o .= '</select>' . PHP_EOL;
129
130                 Hook::callAll(DI::module()->getName() . '_post_' . $selname, $o);
131
132                 return $o;
133         }
134
135         /**
136          * Returns a select input tag with all the contact of the local user
137          *
138          * @param string $selname     Name attribute of the select input tag
139          * @param string $selclass    Class attribute of the select input tag
140          * @param array  $preselected Contact IDs that should be already selected
141          * @param int    $size        Length of the select box
142          * @param int    $tabindex    Select input tag tabindex attribute
143          * @return string
144          * @throws \Exception
145          */
146         public static function getMessageContactSelectHTML($selname, $selclass, array $preselected = [], $size = 4, $tabindex = null)
147         {
148                 $a = DI::app();
149
150                 $o = '';
151
152                 // When used for private messages, we limit correspondence to mutual DFRN/Friendica friends and the selector
153                 // to one recipient. By default our selector allows multiple selects amongst all contacts.
154                 $sql_extra = sprintf(" AND `rel` = %d ", intval(Contact::FRIEND));
155                 $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ", Protocol::DFRN, Protocol::DIASPORA);
156
157                 $tabindex_attr = !empty($tabindex) ? ' tabindex="' . intval($tabindex) . '"' : '';
158
159                 $hidepreselected = '';
160                 if ($preselected) {
161                         $sql_extra .= " AND `id` IN (" . implode(",", $preselected) . ")";
162                         $hidepreselected = ' style="display: none;"';
163                 }
164
165                 $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\"$tabindex_attr$hidepreselected>\r\n";
166
167                 $stmt = DBA::p("SELECT `id`, `name`, `url`, `network` FROM `contact`
168                         WHERE `uid` = ? AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND NOT `deleted` AND `notify` != ''
169                         $sql_extra
170                         ORDER BY `name` ASC ", intval(local_user())
171                 );
172
173                 $contacts = DBA::toArray($stmt);
174
175                 $arr = ['contact' => $contacts, 'entry' => $o];
176
177                 // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
178                 Hook::callAll(DI::module()->getName() . '_pre_' . $selname, $arr);
179
180                 $receiverlist = [];
181
182                 if (DBA::isResult($contacts)) {
183                         foreach ($contacts as $contact) {
184                                 if (in_array($contact['id'], $preselected)) {
185                                         $selected = ' selected="selected"';
186                                 } else {
187                                         $selected = '';
188                                 }
189
190                                 $trimmed = Protocol::formatMention($contact['url'], $contact['name']);
191
192                                 $receiverlist[] = $trimmed;
193
194                                 $o .= "<option value=\"{$contact['id']}\"$selected title=\"{$contact['name']}|{$contact['url']}\" >$trimmed</option>\r\n";
195                         }
196                 }
197
198                 $o .= '</select>' . PHP_EOL;
199
200                 if ($preselected) {
201                         $o .= implode(', ', $receiverlist);
202                 }
203
204                 Hook::callAll(DI::module()->getName() . '_post_' . $selname, $o);
205
206                 return $o;
207         }
208
209         /**
210          * Return the default permission of the provided user array
211          *
212          * @param array $user
213          * @return array Hash of contact id lists
214          * @throws \Exception
215          */
216         public static function getDefaultUserPermissions(array $user = null)
217         {
218                 $aclFormatter = DI::aclFormatter();
219
220                 return [
221                         'allow_cid' => Contact::pruneUnavailable($aclFormatter->expand($user['allow_cid'] ?? '')),
222                         'allow_gid' => $aclFormatter->expand($user['allow_gid'] ?? ''),
223                         'deny_cid'  => $aclFormatter->expand($user['deny_cid']  ?? ''),
224                         'deny_gid'  => $aclFormatter->expand($user['deny_gid']  ?? ''),
225                 ];
226         }
227
228         /**
229          * Returns the ACL list of contacts for a given user id
230          *
231          * @param int   $user_id
232          * @param array $condition Additional contact lookup table conditions
233          * @return array
234          * @throws \Exception
235          */
236         public static function getContactListByUserId(int $user_id, array $condition = [])
237         {
238                 $fields = ['id', 'name', 'addr', 'micro'];
239                 $params = ['order' => ['name']];
240                 $acl_contacts = Contact::selectToArray(
241                         $fields,
242                         array_merge([
243                                 'uid' => $user_id,
244                                 'self' => false,
245                                 'blocked' => false,
246                                 'archive' => false,
247                                 'deleted' => false,
248                                 'pending' => false,
249                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND]
250                         ], $condition),
251                         $params
252                 );
253
254                 $acl_yourself = Contact::selectFirst($fields, ['uid' => $user_id, 'self' => true]);
255                 $acl_yourself['name'] = DI::l10n()->t('Yourself');
256
257                 $acl_contacts[] = $acl_yourself;
258
259                 $acl_forums = Contact::selectToArray($fields,
260                         ['uid' => $user_id, 'self' => false, 'blocked' => false, 'archive' => false, 'deleted' => false,
261                         'pending' => false, 'contact-type' => Contact::TYPE_COMMUNITY], $params
262                 );
263
264                 $acl_contacts = array_merge($acl_forums, $acl_contacts);
265
266                 array_walk($acl_contacts, function (&$value) {
267                         $value['type'] = 'contact';
268                 });
269
270                 return $acl_contacts;
271         }
272
273         /**
274          * Returns the ACL list of groups (including meta-groups) for a given user id
275          *
276          * @param int $user_id
277          * @return array
278          */
279         public static function getGroupListByUserId(int $user_id)
280         {
281                 $acl_groups = [
282                         [
283                                 'id' => Group::FOLLOWERS,
284                                 'name' => DI::l10n()->t('Followers'),
285                                 'addr' => '',
286                                 'micro' => 'images/twopeople.png',
287                                 'type' => 'group',
288                         ],
289                         [
290                                 'id' => Group::MUTUALS,
291                                 'name' => DI::l10n()->t('Mutuals'),
292                                 'addr' => '',
293                                 'micro' => 'images/twopeople.png',
294                                 'type' => 'group',
295                         ]
296                 ];
297                 foreach (Group::getByUserId($user_id) as $group) {
298                         $acl_groups[] = [
299                                 'id' => $group['id'],
300                                 'name' => $group['name'],
301                                 'addr' => '',
302                                 'micro' => 'images/twopeople.png',
303                                 'type' => 'group',
304                         ];
305                 }
306
307                 return $acl_groups;
308         }
309
310         /**
311          * Return the full jot ACL selector HTML
312          *
313          * @param Page   $page
314          * @param array  $user                  User array
315          * @param bool   $for_federation
316          * @param array  $default_permissions   Static defaults permission array:
317          *                                      [
318          *                                      'allow_cid' => [],
319          *                                      'allow_gid' => [],
320          *                                      'deny_cid' => [],
321          *                                      'deny_gid' => [],
322          *                                      'hidewall' => true/false
323          *                                      ]
324          * @param array  $condition
325          * @param string $form_prefix
326          * @return string
327          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
328          */
329         public static function getFullSelectorHTML(
330                 Page $page,
331                 array $user = null,
332                 bool $for_federation = false,
333                 array $default_permissions = [],
334                 array $condition = [],
335                 $form_prefix = ''
336         ) {
337                 if (empty($user['uid'])) {
338                         return '';
339                 }
340
341                 static $input_group_id = 0;
342
343                 $input_group_id++;
344
345                 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
346                 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
347                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
348                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
349
350                 // Defaults user permissions
351                 if (empty($default_permissions)) {
352                         $default_permissions = self::getDefaultUserPermissions($user);
353                 }
354
355                 $default_permissions = [
356                         'allow_cid' => $default_permissions['allow_cid'] ?? [],
357                         'allow_gid' => $default_permissions['allow_gid'] ?? [],
358                         'deny_cid'  => $default_permissions['deny_cid']  ?? [],
359                         'deny_gid'  => $default_permissions['deny_gid']  ?? [],
360                         'hidewall'  => $default_permissions['hidewall']  ?? false,
361                 ];
362
363                 if (count($default_permissions['allow_cid'])
364                         + count($default_permissions['allow_gid'])
365                         + count($default_permissions['deny_cid'])
366                         + count($default_permissions['deny_gid'])) {
367                         $visibility = 'custom';
368                 } else {
369                         $visibility = 'public';
370                         // Default permission display for custom panel
371                         $default_permissions['allow_gid'] = [Group::FOLLOWERS];
372                 }
373
374                 $jotnets_fields = [];
375                 if ($for_federation) {
376                         $mail_enabled = false;
377                         $pubmail_enabled = false;
378
379                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
380                                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $user['uid']]);
381                                 if (DBA::isResult($mailacct)) {
382                                         $mail_enabled = true;
383                                         $pubmail_enabled = !empty($mailacct['pubmail']);
384                                 }
385                         }
386
387                         if (!$default_permissions['hidewall']) {
388                                 if ($mail_enabled) {
389                                         $jotnets_fields[] = [
390                                                 'type' => 'checkbox',
391                                                 'field' => [
392                                                         'pubmail_enable',
393                                                         DI::l10n()->t('Post to Email'),
394                                                         $pubmail_enabled
395                                                 ]
396                                         ];
397                                 }
398
399                                 Hook::callAll('jot_networks', $jotnets_fields);
400                         }
401                 }
402
403                 $acl_contacts = self::getContactListByUserId($user['uid'], $condition);
404
405                 $acl_groups = self::getGroupListByUserId($user['uid']);
406
407                 $acl_list = array_merge($acl_groups, $acl_contacts);
408
409                 $input_names = [
410                         'visibility'    => $form_prefix ? $form_prefix . '[visibility]'    : 'visibility',
411                         'group_allow'   => $form_prefix ? $form_prefix . '[group_allow]'   : 'group_allow',
412                         'contact_allow' => $form_prefix ? $form_prefix . '[contact_allow]' : 'contact_allow',
413                         'group_deny'    => $form_prefix ? $form_prefix . '[group_deny]'    : 'group_deny',
414                         'contact_deny'  => $form_prefix ? $form_prefix . '[contact_deny]'  : 'contact_deny',
415                         'emailcc'       => $form_prefix ? $form_prefix . '[emailcc]'       : 'emailcc',
416                 ];
417
418                 $tpl = Renderer::getMarkupTemplate('acl_selector.tpl');
419                 $o = Renderer::replaceMacros($tpl, [
420                         '$public_title'   => DI::l10n()->t('Public'),
421                         '$public_desc'    => DI::l10n()->t('This content will be shown to all your followers and can be seen in the community pages and by anyone with its link.'),
422                         '$custom_title'   => DI::l10n()->t('Limited/Private'),
423                         '$custom_desc'    => DI::l10n()->t('This content will be shown only to the people in the first box, to the exception of the people mentioned in the second box. It won\'t appear anywhere public.'),
424                         '$allow_label'    => DI::l10n()->t('Show to:'),
425                         '$deny_label'     => DI::l10n()->t('Except to:'),
426                         '$emailcc'        => DI::l10n()->t('CC: email addresses'),
427                         '$emtitle'        => DI::l10n()->t('Example: bob@example.com, mary@example.com'),
428                         '$jotnets_summary' => DI::l10n()->t('Connectors'),
429                         '$jotnets_disabled_label' => DI::l10n()->t('Connectors disabled, since "%s" is enabled.', DI::l10n()->t('Hide your profile details from unknown viewers?')),
430                         '$visibility'     => $visibility,
431                         '$acl_contacts'   => $acl_contacts,
432                         '$acl_groups'     => $acl_groups,
433                         '$acl_list'       => $acl_list,
434                         '$contact_allow'  => implode(',', $default_permissions['allow_cid']),
435                         '$group_allow'    => implode(',', $default_permissions['allow_gid']),
436                         '$contact_deny'   => implode(',', $default_permissions['deny_cid']),
437                         '$group_deny'     => implode(',', $default_permissions['deny_gid']),
438                         '$for_federation' => $for_federation,
439                         '$jotnets_fields' => $jotnets_fields,
440                         '$user_hidewall'  => $default_permissions['hidewall'],
441                         '$input_names'    => $input_names,
442                         '$input_group_id' => $input_group_id,
443                 ]);
444
445                 return $o;
446         }
447 }