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