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