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