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