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