]> git.mxchange.org Git - friendica.git/blob - src/Core/ACL.php
Improve Console/Config display for array values
[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 dba;
10 use Friendica\BaseObject;
11 use Friendica\Content\Feature;
12 use Friendica\Database\DBM;
13 use Friendica\Model\Contact;
14 use Friendica\Model\GContact;
15 use Friendica\Util\Network;
16 use const CONTACT_IS_FRIEND;
17 use const NETWORK_DFRN;
18 use const NETWORK_DIASPORA;
19 use const NETWORK_FACEBOOK;
20 use const NETWORK_MAIL;
21 use const NETWORK_OSTATUS;
22 use const PHP_EOL;
23 use function dbesc;
24 use function defaults;
25 use function get_markup_template;
26 use function get_server;
27 use function local_user;
28 use function remote_user;
29 use function replace_macros;
30
31 /**
32  * Handle ACL management and display
33  *
34  * @author Hypolite Petovan <mrpetovan@gmail.com>
35  */
36 class ACL extends BaseObject
37 {
38         /**
39          * Returns a select input tag with all the contact of the local user
40          *
41          * @param string $selname Name attribute of the select input tag
42          * @param string $selclass Class attribute of the select input tag
43          * @param array $options Available options:
44          * - size: length of the select box
45          * - mutual_friends: Only used for the hook
46          * - single: Only used for the hook
47          * - exclude: Only used for the hook
48          * @param array $preselected Contact ID that should be already selected
49          * @return string
50          */
51         public static function getSuggestContactSelectHTML($selname, $selclass, array $options = [], array $preselected = [])
52         {
53                 $a = self::getApp();
54
55                 $networks = null;
56
57                 $size = defaults($options, 'size', 4);
58                 $mutual = !empty($options['mutual_friends']);
59                 $single = !empty($options['single']) && empty($options['multiple']);
60                 $exclude = defaults($options, 'exclude', false);
61
62                 switch (defaults($options, 'networks', Protocol::PHANTOM)) {
63                         case 'DFRN_ONLY':
64                                 $networks = [NETWORK_DFRN];
65                                 break;
66                         case 'PRIVATE':
67                                 if (!empty($a->user['prvnets'])) {
68                                         $networks = [NETWORK_DFRN, NETWORK_MAIL, NETWORK_DIASPORA];
69                                 } else {
70                                         $networks = [NETWORK_DFRN, NETWORK_FACEBOOK, NETWORK_MAIL, NETWORK_DIASPORA];
71                                 }
72                                 break;
73                         case 'TWO_WAY':
74                                 if (!empty($a->user['prvnets'])) {
75                                         $networks = [NETWORK_DFRN, NETWORK_MAIL, NETWORK_DIASPORA];
76                                 } else {
77                                         $networks = [NETWORK_DFRN, NETWORK_FACEBOOK, NETWORK_MAIL, NETWORK_DIASPORA, NETWORK_OSTATUS];
78                                 }
79                                 break;
80                         default: /// @TODO Maybe log this call?
81                                 break;
82                 }
83
84                 $x = ['options' => $options, 'size' => $size, 'single' => $single, 'mutual' => $mutual, 'exclude' => $exclude, 'networks' => $networks];
85
86                 Addon::callHooks('contact_select_options', $x);
87
88                 $o = '';
89
90                 $sql_extra = '';
91
92                 if (!empty($x['mutual'])) {
93                         $sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
94                 }
95
96                 if (!empty($x['exclude'])) {
97                         $sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude']));
98                 }
99
100                 if (!empty($x['networks'])) {
101                         /// @TODO rewrite to foreach()
102                         array_walk($x['networks'], function (&$value) {
103                                 $value = "'" . dbesc($value) . "'";
104                         });
105                         $str_nets = implode(',', $x['networks']);
106                         $sql_extra .= " AND `network` IN ( $str_nets ) ";
107                 }
108
109                 $tabindex = (!empty($options['tabindex']) ? 'tabindex="' . $options["tabindex"] . '"' : '');
110
111                 if (!empty($x['single'])) {
112                         $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"" . $x['size'] . "\" $tabindex >\r\n";
113                 } else {
114                         $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"" . $x['size'] . "$\" $tabindex >\r\n";
115                 }
116
117                 $stmt = dba::p("SELECT `id`, `name`, `url`, `network` FROM `contact`
118                         WHERE `uid` = ? AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
119                         $sql_extra
120                         ORDER BY `name` ASC ", intval(local_user())
121                 );
122
123                 $contacts = dba::inArray($stmt);
124
125                 $arr = ['contact' => $contacts, 'entry' => $o];
126
127                 // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
128                 Addon::callHooks($a->module . '_pre_' . $selname, $arr);
129
130                 if (DBM::is_result($contacts)) {
131                         foreach ($contacts as $contact) {
132                                 if (in_array($contact['id'], $preselected)) {
133                                         $selected = ' selected="selected" ';
134                                 } else {
135                                         $selected = '';
136                                 }
137
138                                 $trimmed = mb_substr($contact['name'], 0, 20);
139
140                                 $o .= "<option value=\"{$contact['id']}\" $selected title=\"{$contact['name']}|{$contact['url']}\" >$trimmed</option>\r\n";
141                         }
142                 }
143
144                 $o .= '</select>' . PHP_EOL;
145
146                 Addon::callHooks($a->module . '_post_' . $selname, $o);
147
148                 return $o;
149         }
150
151         /**
152          * Returns a select input tag with all the contact of the local user
153          *
154          * @param string $selname     Name attribute of the select input tag
155          * @param string $selclass    Class attribute of the select input tag
156          * @param array  $preselected Contact IDs that should be already selected
157          * @param int    $size        Length of the select box
158          * @param int    $tabindex    Select input tag tabindex attribute
159          * @return string
160          */
161         public static function getMessageContactSelectHTML($selname, $selclass, array $preselected = [], $size = 4, $tabindex = null)
162         {
163                 $a = self::getApp();
164
165                 $o = '';
166
167                 // When used for private messages, we limit correspondence to mutual DFRN/Friendica friends and the selector
168                 // to one recipient. By default our selector allows multiple selects amongst all contacts.
169                 $sql_extra = sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
170                 $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ", NETWORK_DFRN, NETWORK_DIASPORA);
171
172                 $tabindex_attr = !empty($tabindex) ? ' tabindex="' . intval($tabindex) . '"' : '';
173
174                 $hidepreselected = '';
175                 if ($preselected) {
176                         $sql_extra .= " AND `id` IN (" . implode(",", $preselected) . ")";
177                         $hidepreselected = ' style="display: none;"';
178                 }
179
180                 $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\"$tabindex_attr$hidepreselected>\r\n";
181
182                 $stmt = dba::p("SELECT `id`, `name`, `url`, `network` FROM `contact`
183                         WHERE `uid` = ? AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
184                         $sql_extra
185                         ORDER BY `name` ASC ", intval(local_user())
186                 );
187
188                 $contacts = dba::inArray($stmt);
189
190                 $arr = ['contact' => $contacts, 'entry' => $o];
191
192                 // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
193                 Addon::callHooks($a->module . '_pre_' . $selname, $arr);
194
195                 $receiverlist = [];
196
197                 if (DBM::is_result($contacts)) {
198                         foreach ($contacts as $contact) {
199                                 if (in_array($contact['id'], $preselected)) {
200                                         $selected = ' selected="selected"';
201                                 } else {
202                                         $selected = '';
203                                 }
204
205                                 $trimmed = Protocol::formatMention($contact['url'], $contact['name']);
206
207                                 $receiverlist[] = $trimmed;
208
209                                 $o .= "<option value=\"{$contact['id']}\"$selected title=\"{$contact['name']}|{$contact['url']}\" >$trimmed</option>\r\n";
210                         }
211                 }
212
213                 $o .= '</select>' . PHP_EOL;
214
215                 if ($preselected) {
216                         $o .= implode(', ', $receiverlist);
217                 }
218
219                 Addon::callHooks($a->module . '_post_' . $selname, $o);
220
221                 return $o;
222         }
223
224         private static function fixACL(&$item)
225         {
226                 $item = intval(str_replace(['<', '>'], ['', ''], $item));
227         }
228
229         /**
230          * Return the default permission of the provided user array
231          *
232          * @param array $user
233          * @return array Hash of contact id lists
234          */
235         public static function getDefaultUserPermissions(array $user = null)
236         {
237                 $matches = [];
238
239                 $acl_regex = '/<([0-9]+)>/i';
240
241                 preg_match_all($acl_regex, defaults($user, 'allow_cid', ''), $matches);
242                 $allow_cid = $matches[1];
243                 preg_match_all($acl_regex, defaults($user, 'allow_gid', ''), $matches);
244                 $allow_gid = $matches[1];
245                 preg_match_all($acl_regex, defaults($user, 'deny_cid', ''), $matches);
246                 $deny_cid = $matches[1];
247                 preg_match_all($acl_regex, defaults($user, 'deny_gid', ''), $matches);
248                 $deny_gid = $matches[1];
249
250                 // Reformats the ACL data so that it is accepted by the JS frontend
251                 array_walk($allow_cid, 'self::fixACL');
252                 array_walk($allow_gid, 'self::fixACL');
253                 array_walk($deny_cid, 'self::fixACL');
254                 array_walk($deny_gid, 'self::fixACL');
255
256                 Contact::pruneUnavailable($allow_cid);
257
258                 return [
259                         'allow_cid' => $allow_cid,
260                         'allow_gid' => $allow_gid,
261                         'deny_cid' => $deny_cid,
262                         'deny_gid' => $deny_gid,
263                 ];
264         }
265
266         /**
267          * Return the full jot ACL selector HTML
268          *
269          * @param array $user
270          * @param bool  $show_jotnets
271          * @return string
272          */
273         public static function getFullSelectorHTML(array $user = null, $show_jotnets = false)
274         {
275                 $perms = self::getDefaultUserPermissions($user);
276
277                 $jotnets = '';
278                 if ($show_jotnets) {
279                         $imap_disabled = !function_exists('imap_open') || Config::get('system', 'imap_disabled');
280
281                         $mail_enabled = false;
282                         $pubmail_enabled = false;
283
284                         if (!$imap_disabled) {
285                                 $mailacct = dba::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', local_user()]);
286                                 if (DBM::is_result($mailacct)) {
287                                         $mail_enabled = true;
288                                         $pubmail_enabled = !empty($mailacct['pubmail']);
289                                 }
290                         }
291
292                         if (empty($user['hidewall'])) {
293                                 if ($mail_enabled) {
294                                         $selected = $pubmail_enabled ? ' checked="checked"' : '';
295                                         $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . L10n::t("Post to Email") . '</div>';
296                                 }
297
298                                 Addon::callHooks('jot_networks', $jotnets);
299                         } else {
300                                 $jotnets .= L10n::t('Connectors disabled, since "%s" is enabled.',
301                                                 L10n::t('Hide your profile details from unknown viewers?'));
302                         }
303                 }
304
305                 $tpl = get_markup_template('acl_selector.tpl');
306                 $o = replace_macros($tpl, [
307                         '$showall' => L10n::t('Visible to everybody'),
308                         '$show' => L10n::t('show'),
309                         '$hide' => L10n::t('don\'t show'),
310                         '$allowcid' => json_encode($perms['allow_cid']),
311                         '$allowgid' => json_encode($perms['allow_gid']),
312                         '$denycid' => json_encode($perms['deny_cid']),
313                         '$denygid' => json_encode($perms['deny_gid']),
314                         '$networks' => $show_jotnets,
315                         '$emailcc' => L10n::t('CC: email addresses'),
316                         '$emtitle' => L10n::t('Example: bob@example.com, mary@example.com'),
317                         '$jotnets' => $jotnets,
318                         '$aclModalTitle' => L10n::t('Permissions'),
319                         '$aclModalDismiss' => L10n::t('Close'),
320                         '$features' => [
321                                 'aclautomention' => Feature::isEnabled($user['uid'], 'aclautomention') ? 'true' : 'false'
322                         ],
323                 ]);
324
325                 return $o;
326         }
327
328         /**
329          * Searching for global contacts for autocompletion
330          *
331          * @brief Searching for global contacts for autocompletion
332          * @param string $search Name or part of a name or nick
333          * @param string $mode   Search mode (e.g. "community")
334          * @return array with the search results
335          */
336         public static function contactAutocomplete($search, $mode)
337         {
338                 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
339                         return [];
340                 }
341
342                 // don't search if search term has less than 2 characters
343                 if (!$search || mb_strlen($search) < 2) {
344                         return [];
345                 }
346
347                 if (substr($search, 0, 1) === '@') {
348                         $search = substr($search, 1);
349                 }
350
351                 // check if searching in the local global contact table is enabled
352                 if (Config::get('system', 'poco_local_search')) {
353                         $return = GContact::searchByName($search, $mode);
354                 } else {
355                         $a = self::getApp();
356                         $p = $a->pager['page'] != 1 ? '&p=' . $a->pager['page'] : '';
357
358                         $response = Network::curl(get_server() . '/lsearch?f=' . $p . '&search=' . urlencode($search));
359                         if ($response['success']) {
360                                 $lsearch = json_decode($response['body'], true);
361                                 if (!empty($lsearch['results'])) {
362                                         $return = $lsearch['results'];
363                                 }
364                         }
365                 }
366
367                 return defaults($return, []);
368         }
369 }