]> git.mxchange.org Git - friendica.git/blob - src/Core/ACL.php
45f8e1128bd52758796156d17ad0322f0c6a2cda
[friendica.git] / src / Core / ACL.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
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\Core;
23
24 use Friendica\App\Page;
25 use Friendica\Database\DBA;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28 use Friendica\Model\Group;
29 use Friendica\Model\User;
30
31 /**
32  * Handle ACL management and display
33  */
34 class ACL
35 {
36         /**
37          * Returns the default lock state for the given user id
38          * @param int $uid
39          * @return bool "true" if the default settings are non public
40          */
41         public static function getLockstateForUserId(int $uid)
42         {
43                 $user = User::getById($uid, ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid']);
44                 return !empty($user['allow_cid']) || !empty($user['allow_gid']) || !empty($user['deny_cid']) || !empty($user['deny_gid']);
45         }
46
47         /**
48          * Returns a select input tag for private message recipient
49          *
50          * @param int  $selected Existing recipien contact ID
51          * @return string
52          * @throws \Exception
53          */
54         public static function getMessageContactSelectHTML(int $selected = null): string
55         {
56                 $o = '';
57
58                 $page = DI::page();
59
60                 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
61                 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
62                 $page->registerFooterScript(Theme::getPathForFile('../vendor/enyo/dropzone/dist/min/dropzone.min.js'));
63                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
64                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
65                 $page->registerStylesheet(Theme::getPathForFile('../vendor/enyo/dropzone/dist/min/dropzone.min.css'));
66
67                 $contacts = self::getValidMessageRecipientsForUser(DI::userSession()->getLocalUserId());
68
69                 $tpl = Renderer::getMarkupTemplate('acl/message_recipient.tpl');
70                 $o = Renderer::replaceMacros($tpl, [
71                         '$contacts' => $contacts,
72                         '$selected' => $selected,
73                 ]);
74
75                 Hook::callAll(DI::args()->getModuleName() . '_post_recipient', $o);
76
77                 return $o;
78         }
79
80         public static function getValidMessageRecipientsForUser(int $uid): array
81         {
82                 $condition = [
83                         'uid'     => $uid,
84                         'self'    => false,
85                         'blocked' => false,
86                         'pending' => false,
87                         'archive' => false,
88                         'deleted' => false,
89                         'rel'     => [Contact::FOLLOWER, Contact::SHARING, Contact::FRIEND],
90                         'network' => Protocol::SUPPORT_PRIVATE,
91                 ];
92
93                 return Contact::selectToArray(
94                         ['id', 'name', 'addr', 'micro', 'url', 'nick'],
95                         DBA::mergeConditions($condition, ["`notify` != ''"])
96                 );
97         }
98
99         /**
100          * Returns a minimal ACL block for self-only permissions
101          *
102          * @param int    $localUserId
103          * @param string $explanation
104          * @return string
105          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
106          */
107         public static function getSelfOnlyHTML(int $localUserId, string $explanation)
108         {
109                 $selfPublicContactId = Contact::getPublicIdByUserId($localUserId);
110
111                 $tpl = Renderer::getMarkupTemplate('acl/self_only.tpl');
112                 $o = Renderer::replaceMacros($tpl, [
113                         '$selfPublicContactId' => $selfPublicContactId,
114                         '$explanation' => $explanation,
115                 ]);
116
117                 return $o;
118         }
119
120         /**
121          * Return the default permission of the provided user array
122          *
123          * @param array $user
124          * @return array Hash of contact id lists
125          * @throws \Exception
126          */
127         public static function getDefaultUserPermissions(array $user = null)
128         {
129                 $aclFormatter = DI::aclFormatter();
130
131                 return [
132                         'allow_cid' => Contact::pruneUnavailable($aclFormatter->expand($user['allow_cid'] ?? '')),
133                         'allow_gid' => $aclFormatter->expand($user['allow_gid'] ?? ''),
134                         'deny_cid'  => $aclFormatter->expand($user['deny_cid']  ?? ''),
135                         'deny_gid'  => $aclFormatter->expand($user['deny_gid']  ?? ''),
136                 ];
137         }
138
139         /**
140          * Returns the ACL list of contacts for a given user id
141          *
142          * @param int   $user_id
143          * @param array $condition Additional contact lookup table conditions
144          * @return array
145          * @throws \Exception
146          */
147         public static function getContactListByUserId(int $user_id, array $condition = [])
148         {
149                 $fields = ['id', 'name', 'addr', 'micro'];
150                 $params = ['order' => ['name']];
151                 $acl_contacts = Contact::selectToArray(
152                         $fields,
153                         array_merge([
154                                 'uid' => $user_id,
155                                 'self' => false,
156                                 'blocked' => false,
157                                 'archive' => false,
158                                 'deleted' => false,
159                                 'pending' => false,
160                                 'network' => Protocol::FEDERATED,
161                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND]
162                         ], $condition),
163                         $params
164                 );
165
166                 $acl_yourself = Contact::selectFirst($fields, ['uid' => $user_id, 'self' => true]);
167                 $acl_yourself['name'] = DI::l10n()->t('Yourself');
168
169                 $acl_contacts[] = $acl_yourself;
170
171                 $acl_forums = Contact::selectToArray($fields,
172                         ['uid' => $user_id, 'self' => false, 'blocked' => false, 'archive' => false, 'deleted' => false,
173                         'network' => Protocol::FEDERATED, 'pending' => false, 'contact-type' => Contact::TYPE_COMMUNITY], $params
174                 );
175
176                 $acl_contacts = array_merge($acl_forums, $acl_contacts);
177
178                 array_walk($acl_contacts, function (&$value) {
179                         $value['type'] = 'contact';
180                 });
181
182                 return $acl_contacts;
183         }
184
185         /**
186          * Returns the ACL list of groups (including meta-groups) for a given user id
187          *
188          * @param int $user_id
189          * @return array
190          */
191         public static function getGroupListByUserId(int $user_id)
192         {
193                 $acl_groups = [
194                         [
195                                 'id' => Group::FOLLOWERS,
196                                 'name' => DI::l10n()->t('Followers'),
197                                 'addr' => '',
198                                 'micro' => 'images/twopeople.png',
199                                 'type' => 'group',
200                         ],
201                         [
202                                 'id' => Group::MUTUALS,
203                                 'name' => DI::l10n()->t('Mutuals'),
204                                 'addr' => '',
205                                 'micro' => 'images/twopeople.png',
206                                 'type' => 'group',
207                         ]
208                 ];
209                 foreach (Group::getByUserId($user_id) as $group) {
210                         $acl_groups[] = [
211                                 'id' => $group['id'],
212                                 'name' => $group['name'],
213                                 'addr' => '',
214                                 'micro' => 'images/twopeople.png',
215                                 'type' => 'group',
216                         ];
217                 }
218
219                 return $acl_groups;
220         }
221
222         /**
223          * Return the full jot ACL selector HTML
224          *
225          * @param Page   $page
226          * @param int    $uid                   User ID
227          * @param bool   $for_federation
228          * @param array  $default_permissions   Static defaults permission array:
229          *                                      [
230          *                                      'allow_cid' => [],
231          *                                      'allow_gid' => [],
232          *                                      'deny_cid' => [],
233          *                                      'deny_gid' => []
234          *                                      ]
235          * @param array  $condition
236          * @param string $form_prefix
237          * @return string
238          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
239          */
240         public static function getFullSelectorHTML(
241                 Page $page,
242                 int $uid = null,
243                 bool $for_federation = false,
244                 array $default_permissions = [],
245                 array $condition = [],
246                 $form_prefix = ''
247         ) {
248                 if (empty($uid)) {
249                         return '';
250                 }
251
252                 static $input_group_id = 0;
253
254                 $user = User::getById($uid);
255
256                 $input_group_id++;
257
258                 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
259                 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
260                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
261                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
262
263                 // Defaults user permissions
264                 if (empty($default_permissions)) {
265                         $default_permissions = self::getDefaultUserPermissions($user);
266                 }
267
268                 $default_permissions = [
269                         'allow_cid' => $default_permissions['allow_cid'] ?? [],
270                         'allow_gid' => $default_permissions['allow_gid'] ?? [],
271                         'deny_cid'  => $default_permissions['deny_cid']  ?? [],
272                         'deny_gid'  => $default_permissions['deny_gid']  ?? [],
273                 ];
274
275                 if (count($default_permissions['allow_cid'])
276                         + count($default_permissions['allow_gid'])
277                         + count($default_permissions['deny_cid'])
278                         + count($default_permissions['deny_gid'])) {
279                         $visibility = 'custom';
280                 } else {
281                         $visibility = 'public';
282                         // Default permission display for custom panel
283                         $default_permissions['allow_gid'] = [Group::FOLLOWERS];
284                 }
285
286                 $jotnets_fields = [];
287                 if ($for_federation) {
288                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
289                                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $user['uid']]);
290                                 if (DBA::isResult($mailacct)) {
291                                         $jotnets_fields[] = [
292                                                 'type' => 'checkbox',
293                                                 'field' => [
294                                                         'pubmail_enable',
295                                                         DI::l10n()->t('Post to Email'),
296                                                         !empty($mailacct['pubmail'])
297                                                 ]
298                                         ];
299
300                                 }
301                         }
302                         Hook::callAll('jot_networks', $jotnets_fields);
303                 }
304
305                 $acl_contacts = self::getContactListByUserId($user['uid'], $condition);
306
307                 $acl_groups = self::getGroupListByUserId($user['uid']);
308
309                 $acl_list = array_merge($acl_groups, $acl_contacts);
310
311                 $input_names = [
312                         'visibility'    => $form_prefix ? $form_prefix . '[visibility]'    : 'visibility',
313                         'group_allow'   => $form_prefix ? $form_prefix . '[group_allow]'   : 'group_allow',
314                         'contact_allow' => $form_prefix ? $form_prefix . '[contact_allow]' : 'contact_allow',
315                         'group_deny'    => $form_prefix ? $form_prefix . '[group_deny]'    : 'group_deny',
316                         'contact_deny'  => $form_prefix ? $form_prefix . '[contact_deny]'  : 'contact_deny',
317                         'emailcc'       => $form_prefix ? $form_prefix . '[emailcc]'       : 'emailcc',
318                 ];
319
320                 $tpl = Renderer::getMarkupTemplate('acl/full_selector.tpl');
321                 $o = Renderer::replaceMacros($tpl, [
322                         '$public_title'   => DI::l10n()->t('Public'),
323                         '$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.'),
324                         '$custom_title'   => DI::l10n()->t('Limited/Private'),
325                         '$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.') . DI::l10n()->t('Start typing the name of a contact or a group to show a filtered list. You can also mention the special groups "Followers" and "Mutuals".'),
326                         '$allow_label'    => DI::l10n()->t('Show to:'),
327                         '$deny_label'     => DI::l10n()->t('Except to:'),
328                         '$emailcc'        => DI::l10n()->t('CC: email addresses'),
329                         '$emtitle'        => DI::l10n()->t('Example: bob@example.com, mary@example.com'),
330                         '$jotnets_summary' => DI::l10n()->t('Connectors'),
331                         '$visibility'     => $visibility,
332                         '$acl_contacts'   => $acl_contacts,
333                         '$acl_groups'     => $acl_groups,
334                         '$acl_list'       => $acl_list,
335                         '$contact_allow'  => implode(',', $default_permissions['allow_cid']),
336                         '$group_allow'    => implode(',', $default_permissions['allow_gid']),
337                         '$contact_deny'   => implode(',', $default_permissions['deny_cid']),
338                         '$group_deny'     => implode(',', $default_permissions['deny_gid']),
339                         '$for_federation' => $for_federation,
340                         '$jotnets_fields' => $jotnets_fields,
341                         '$input_names'    => $input_names,
342                         '$input_group_id' => $input_group_id,
343                 ]);
344
345                 return $o;
346         }
347
348         /**
349          * Checks the validity of the given ACL string
350          *
351          * @param string $acl_string
352          * @param int    $uid
353          * @return bool
354          * @throws Exception
355          */
356         public static function isValidContact($acl_string, $uid)
357         {
358                 if (empty($acl_string)) {
359                         return true;
360                 }
361
362                 // split <x><y><z> into array of cids
363                 preg_match_all('/<[A-Za-z0-9]+>/', $acl_string, $array);
364
365                 // check for each cid if the contact is valid for the given user
366                 $cid_array = $array[0];
367                 foreach ($cid_array as $cid) {
368                         $cid = str_replace(['<', '>'], ['', ''], $cid);
369                         if (!DBA::exists('contact', ['id' => $cid, 'uid' => $uid])) {
370                                 return false;
371                         }
372                 }
373
374                 return true;
375         }
376
377         /**
378          * Checks the validity of the given ACL string
379          *
380          * @param string $acl_string
381          * @param int    $uid
382          * @return bool
383          * @throws Exception
384          */
385         public static function isValidGroup($acl_string, $uid)
386         {
387                 if (empty($acl_string)) {
388                         return true;
389                 }
390
391                 // split <x><y><z> into array of cids
392                 preg_match_all('/<[A-Za-z0-9]+>/', $acl_string, $array);
393
394                 // check for each cid if the contact is valid for the given user
395                 $gid_array = $array[0];
396                 foreach ($gid_array as $gid) {
397                         $gid = str_replace(['<', '>'], ['', ''], $gid);
398                         if (!DBA::exists('group', ['id' => $gid, 'uid' => $uid, 'deleted' => false])) {
399                                 return false;
400                         }
401                 }
402
403                 return true;
404         }
405 }