5f69d78b683921cccca5c75a9d3a3340d1bd700e
[friendica.git/.git] / src / Core / 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\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
30 /**
31  * Handle ACL management and display
32  */
33 class ACL
34 {
35         /**
36          * Returns a select input tag for private message recipient
37          *
38          * @param int  $selected Existing recipien contact ID
39          * @return string
40          * @throws \Exception
41          */
42         public static function getMessageContactSelectHTML(int $selected = null)
43         {
44                 $o = '';
45
46                 $page = DI::page();
47
48                 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
49                 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
50                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
51                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
52
53                 // When used for private messages, we limit correspondence to mutual DFRN/Friendica friends and the selector
54                 // to one recipient. By default our selector allows multiple selects amongst all contacts.
55                 $condition = [
56                         'uid' => local_user(),
57                         'self' => false,
58                         'blocked' => false,
59                         'pending' => false,
60                         'archive' => false,
61                         'deleted' => false,
62                         'rel' => [Contact::FOLLOWER, Contact::SHARING, Contact::FRIEND],
63                         'network' => Protocol::FEDERATED,
64                 ];
65
66                 $contacts = Contact::selectToArray(
67                         ['id', 'name', 'addr', 'micro'],
68                         DBA::mergeConditions($condition, ["`notify` != ''"])
69                 );
70
71                 $arr = ['contact' => $contacts, 'entry' => $o];
72
73                 Hook::callAll(DI::module()->getName() . '_pre_recipient', $arr);
74
75                 $tpl = Renderer::getMarkupTemplate('acl/message_recipient.tpl');
76                 $o = Renderer::replaceMacros($tpl, [
77                         '$contacts' => $contacts,
78                         '$selected' => $selected,
79                 ]);
80
81                 Hook::callAll(DI::module()->getName() . '_post_recipient', $o);
82
83                 return $o;
84         }
85
86         /**
87          * Returns a minimal ACL block for self-only permissions
88          *
89          * @param int    $localUserId
90          * @param string $explanation
91          * @return string
92          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
93          */
94         public static function getSelfOnlyHTML(int $localUserId, string $explanation)
95         {
96                 $selfPublicContactId = Contact::getPublicIdByUserId($localUserId);
97
98                 $tpl = Renderer::getMarkupTemplate('acl/self_only.tpl');
99                 $o = Renderer::replaceMacros($tpl, [
100                         '$selfPublicContactId' => $selfPublicContactId,
101                         '$explanation' => $explanation,
102                 ]);
103
104                 return $o;
105         }
106
107         /**
108          * Return the default permission of the provided user array
109          *
110          * @param array $user
111          * @return array Hash of contact id lists
112          * @throws \Exception
113          */
114         public static function getDefaultUserPermissions(array $user = null)
115         {
116                 $aclFormatter = DI::aclFormatter();
117
118                 return [
119                         'allow_cid' => Contact::pruneUnavailable($aclFormatter->expand($user['allow_cid'] ?? '')),
120                         'allow_gid' => $aclFormatter->expand($user['allow_gid'] ?? ''),
121                         'deny_cid'  => $aclFormatter->expand($user['deny_cid']  ?? ''),
122                         'deny_gid'  => $aclFormatter->expand($user['deny_gid']  ?? ''),
123                 ];
124         }
125
126         /**
127          * Returns the ACL list of contacts for a given user id
128          *
129          * @param int   $user_id
130          * @param array $condition Additional contact lookup table conditions
131          * @return array
132          * @throws \Exception
133          */
134         public static function getContactListByUserId(int $user_id, array $condition = [])
135         {
136                 $fields = ['id', 'name', 'addr', 'micro'];
137                 $params = ['order' => ['name']];
138                 $acl_contacts = Contact::selectToArray(
139                         $fields,
140                         array_merge([
141                                 'uid' => $user_id,
142                                 'self' => false,
143                                 'blocked' => false,
144                                 'archive' => false,
145                                 'deleted' => false,
146                                 'pending' => false,
147                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND]
148                         ], $condition),
149                         $params
150                 );
151
152                 $acl_yourself = Contact::selectFirst($fields, ['uid' => $user_id, 'self' => true]);
153                 $acl_yourself['name'] = DI::l10n()->t('Yourself');
154
155                 $acl_contacts[] = $acl_yourself;
156
157                 $acl_forums = Contact::selectToArray($fields,
158                         ['uid' => $user_id, 'self' => false, 'blocked' => false, 'archive' => false, 'deleted' => false,
159                         'pending' => false, 'contact-type' => Contact::TYPE_COMMUNITY], $params
160                 );
161
162                 $acl_contacts = array_merge($acl_forums, $acl_contacts);
163
164                 array_walk($acl_contacts, function (&$value) {
165                         $value['type'] = 'contact';
166                 });
167
168                 return $acl_contacts;
169         }
170
171         /**
172          * Returns the ACL list of groups (including meta-groups) for a given user id
173          *
174          * @param int $user_id
175          * @return array
176          */
177         public static function getGroupListByUserId(int $user_id)
178         {
179                 $acl_groups = [
180                         [
181                                 'id' => Group::FOLLOWERS,
182                                 'name' => DI::l10n()->t('Followers'),
183                                 'addr' => '',
184                                 'micro' => 'images/twopeople.png',
185                                 'type' => 'group',
186                         ],
187                         [
188                                 'id' => Group::MUTUALS,
189                                 'name' => DI::l10n()->t('Mutuals'),
190                                 'addr' => '',
191                                 'micro' => 'images/twopeople.png',
192                                 'type' => 'group',
193                         ]
194                 ];
195                 foreach (Group::getByUserId($user_id) as $group) {
196                         $acl_groups[] = [
197                                 'id' => $group['id'],
198                                 'name' => $group['name'],
199                                 'addr' => '',
200                                 'micro' => 'images/twopeople.png',
201                                 'type' => 'group',
202                         ];
203                 }
204
205                 return $acl_groups;
206         }
207
208         /**
209          * Return the full jot ACL selector HTML
210          *
211          * @param Page   $page
212          * @param array  $user                  User array
213          * @param bool   $for_federation
214          * @param array  $default_permissions   Static defaults permission array:
215          *                                      [
216          *                                      'allow_cid' => [],
217          *                                      'allow_gid' => [],
218          *                                      'deny_cid' => [],
219          *                                      'deny_gid' => []
220          *                                      ]
221          * @param array  $condition
222          * @param string $form_prefix
223          * @return string
224          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225          */
226         public static function getFullSelectorHTML(
227                 Page $page,
228                 array $user = null,
229                 bool $for_federation = false,
230                 array $default_permissions = [],
231                 array $condition = [],
232                 $form_prefix = ''
233         ) {
234                 if (empty($user['uid'])) {
235                         return '';
236                 }
237
238                 static $input_group_id = 0;
239
240                 $input_group_id++;
241
242                 $page->registerFooterScript(Theme::getPathForFile('asset/typeahead.js/dist/typeahead.bundle.js'));
243                 $page->registerFooterScript(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.js'));
244                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput.css'));
245                 $page->registerStylesheet(Theme::getPathForFile('js/friendica-tagsinput/friendica-tagsinput-typeahead.css'));
246
247                 // Defaults user permissions
248                 if (empty($default_permissions)) {
249                         $default_permissions = self::getDefaultUserPermissions($user);
250                 }
251
252                 $default_permissions = [
253                         'allow_cid' => $default_permissions['allow_cid'] ?? [],
254                         'allow_gid' => $default_permissions['allow_gid'] ?? [],
255                         'deny_cid'  => $default_permissions['deny_cid']  ?? [],
256                         'deny_gid'  => $default_permissions['deny_gid']  ?? [],
257                 ];
258
259                 if (count($default_permissions['allow_cid'])
260                         + count($default_permissions['allow_gid'])
261                         + count($default_permissions['deny_cid'])
262                         + count($default_permissions['deny_gid'])) {
263                         $visibility = 'custom';
264                 } else {
265                         $visibility = 'public';
266                         // Default permission display for custom panel
267                         $default_permissions['allow_gid'] = [Group::FOLLOWERS];
268                 }
269
270                 $jotnets_fields = [];
271                 if ($for_federation) {
272                         if (function_exists('imap_open') && !DI::config()->get('system', 'imap_disabled')) {
273                                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', $user['uid']]);
274                                 if (DBA::isResult($mailacct)) {
275                                         $jotnets_fields[] = [
276                                                 'type' => 'checkbox',
277                                                 'field' => [
278                                                         'pubmail_enable',
279                                                         DI::l10n()->t('Post to Email'),
280                                                         !empty($mailacct['pubmail'])
281                                                 ]
282                                         ];
283         
284                                 }
285                         }
286                         Hook::callAll('jot_networks', $jotnets_fields);
287                 }
288
289                 $acl_contacts = self::getContactListByUserId($user['uid'], $condition);
290
291                 $acl_groups = self::getGroupListByUserId($user['uid']);
292
293                 $acl_list = array_merge($acl_groups, $acl_contacts);
294
295                 $input_names = [
296                         'visibility'    => $form_prefix ? $form_prefix . '[visibility]'    : 'visibility',
297                         'group_allow'   => $form_prefix ? $form_prefix . '[group_allow]'   : 'group_allow',
298                         'contact_allow' => $form_prefix ? $form_prefix . '[contact_allow]' : 'contact_allow',
299                         'group_deny'    => $form_prefix ? $form_prefix . '[group_deny]'    : 'group_deny',
300                         'contact_deny'  => $form_prefix ? $form_prefix . '[contact_deny]'  : 'contact_deny',
301                         'emailcc'       => $form_prefix ? $form_prefix . '[emailcc]'       : 'emailcc',
302                 ];
303
304                 $tpl = Renderer::getMarkupTemplate('acl/full_selector.tpl');
305                 $o = Renderer::replaceMacros($tpl, [
306                         '$public_title'   => DI::l10n()->t('Public'),
307                         '$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.'),
308                         '$custom_title'   => DI::l10n()->t('Limited/Private'),
309                         '$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.'),
310                         '$allow_label'    => DI::l10n()->t('Show to:'),
311                         '$deny_label'     => DI::l10n()->t('Except to:'),
312                         '$emailcc'        => DI::l10n()->t('CC: email addresses'),
313                         '$emtitle'        => DI::l10n()->t('Example: bob@example.com, mary@example.com'),
314                         '$jotnets_summary' => DI::l10n()->t('Connectors'),
315                         '$visibility'     => $visibility,
316                         '$acl_contacts'   => $acl_contacts,
317                         '$acl_groups'     => $acl_groups,
318                         '$acl_list'       => $acl_list,
319                         '$contact_allow'  => implode(',', $default_permissions['allow_cid']),
320                         '$group_allow'    => implode(',', $default_permissions['allow_gid']),
321                         '$contact_deny'   => implode(',', $default_permissions['deny_cid']),
322                         '$group_deny'     => implode(',', $default_permissions['deny_gid']),
323                         '$for_federation' => $for_federation,
324                         '$jotnets_fields' => $jotnets_fields,
325                         '$input_names'    => $input_names,
326                         '$input_group_id' => $input_group_id,
327                 ]);
328
329                 return $o;
330         }
331 }