]> git.mxchange.org Git - friendica.git/blob - src/Core/ACL.php
5cb24595704f0534c73b80e6e73fea9005fec18b
[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\Model\Contact;
13 use Friendica\Model\GContact;
14 use Friendica\Util\Network;
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          */
36         public static function getSuggestContactSelectHTML($selname, $selclass, array $options = [], array $preselected = [])
37         {
38                 $a = self::getApp();
39
40                 $networks = null;
41
42                 $size = defaults($options, 'size', 4);
43                 $mutual = !empty($options['mutual_friends']);
44                 $single = !empty($options['single']) && empty($options['multiple']);
45                 $exclude = defaults($options, 'exclude', false);
46
47                 switch (defaults($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          */
145         public static function getMessageContactSelectHTML($selname, $selclass, array $preselected = [], $size = 4, $tabindex = null)
146         {
147                 $a = self::getApp();
148
149                 $o = '';
150
151                 // When used for private messages, we limit correspondence to mutual DFRN/Friendica friends and the selector
152                 // to one recipient. By default our selector allows multiple selects amongst all contacts.
153                 $sql_extra = sprintf(" AND `rel` = %d ", intval(Contact::FRIEND));
154                 $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ", Protocol::DFRN, Protocol::DIASPORA);
155
156                 $tabindex_attr = !empty($tabindex) ? ' tabindex="' . intval($tabindex) . '"' : '';
157
158                 $hidepreselected = '';
159                 if ($preselected) {
160                         $sql_extra .= " AND `id` IN (" . implode(",", $preselected) . ")";
161                         $hidepreselected = ' style="display: none;"';
162                 }
163
164                 $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\"$tabindex_attr$hidepreselected>\r\n";
165
166                 $stmt = DBA::p("SELECT `id`, `name`, `url`, `network` FROM `contact`
167                         WHERE `uid` = ? AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND NOT `deleted` AND `notify` != ''
168                         $sql_extra
169                         ORDER BY `name` ASC ", intval(local_user())
170                 );
171
172                 $contacts = DBA::toArray($stmt);
173
174                 $arr = ['contact' => $contacts, 'entry' => $o];
175
176                 // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
177                 Hook::callAll($a->module . '_pre_' . $selname, $arr);
178
179                 $receiverlist = [];
180
181                 if (DBA::isResult($contacts)) {
182                         foreach ($contacts as $contact) {
183                                 if (in_array($contact['id'], $preselected)) {
184                                         $selected = ' selected="selected"';
185                                 } else {
186                                         $selected = '';
187                                 }
188
189                                 $trimmed = Protocol::formatMention($contact['url'], $contact['name']);
190
191                                 $receiverlist[] = $trimmed;
192
193                                 $o .= "<option value=\"{$contact['id']}\"$selected title=\"{$contact['name']}|{$contact['url']}\" >$trimmed</option>\r\n";
194                         }
195                 }
196
197                 $o .= '</select>' . PHP_EOL;
198
199                 if ($preselected) {
200                         $o .= implode(', ', $receiverlist);
201                 }
202
203                 Hook::callAll($a->module . '_post_' . $selname, $o);
204
205                 return $o;
206         }
207
208         private static function fixACL(&$item)
209         {
210                 $item = intval(str_replace(['<', '>'], ['', ''], $item));
211         }
212
213         /**
214          * Return the default permission of the provided user array
215          *
216          * @param array $user
217          * @return array Hash of contact id lists
218          */
219         public static function getDefaultUserPermissions(array $user = null)
220         {
221                 $matches = [];
222
223                 $acl_regex = '/<([0-9]+)>/i';
224
225                 preg_match_all($acl_regex, defaults($user, 'allow_cid', ''), $matches);
226                 $allow_cid = $matches[1];
227                 preg_match_all($acl_regex, defaults($user, 'allow_gid', ''), $matches);
228                 $allow_gid = $matches[1];
229                 preg_match_all($acl_regex, defaults($user, 'deny_cid', ''), $matches);
230                 $deny_cid = $matches[1];
231                 preg_match_all($acl_regex, defaults($user, 'deny_gid', ''), $matches);
232                 $deny_gid = $matches[1];
233
234                 // Reformats the ACL data so that it is accepted by the JS frontend
235                 array_walk($allow_cid, 'self::fixACL');
236                 array_walk($allow_gid, 'self::fixACL');
237                 array_walk($deny_cid, 'self::fixACL');
238                 array_walk($deny_gid, 'self::fixACL');
239
240                 Contact::pruneUnavailable($allow_cid);
241
242                 return [
243                         'allow_cid' => $allow_cid,
244                         'allow_gid' => $allow_gid,
245                         'deny_cid' => $deny_cid,
246                         'deny_gid' => $deny_gid,
247                 ];
248         }
249
250         /**
251          * Return the full jot ACL selector HTML
252          *
253          * @param array $user                User array
254          * @param array $default_permissions Static defaults permission array: ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']
255          * @param bool  $show_jotnets
256          * @return string
257          */
258         public static function getFullSelectorHTML(array $user, $show_jotnets = false, array $default_permissions = [])
259         {
260                 // Defaults user permissions
261                 if (empty($default_permissions)) {
262                         $default_permissions = self::getDefaultUserPermissions($user);
263                 }
264
265                 $jotnets = '';
266                 if ($show_jotnets) {
267                         $imap_disabled = !function_exists('imap_open') || Config::get('system', 'imap_disabled');
268
269                         $mail_enabled = false;
270                         $pubmail_enabled = false;
271
272                         if (!$imap_disabled) {
273                                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', local_user()]);
274                                 if (DBA::isResult($mailacct)) {
275                                         $mail_enabled = true;
276                                         $pubmail_enabled = !empty($mailacct['pubmail']);
277                                 }
278                         }
279
280                         if (empty($default_permissions['hidewall'])) {
281                                 if ($mail_enabled) {
282                                         $selected = $pubmail_enabled ? ' checked="checked"' : '';
283                                         $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . L10n::t("Post to Email") . '</div>';
284                                 }
285
286                                 Hook::callAll('jot_networks', $jotnets);
287                         } else {
288                                 $jotnets .= L10n::t('Connectors disabled, since "%s" is enabled.',
289                                                 L10n::t('Hide your profile details from unknown viewers?'));
290                         }
291                 }
292
293                 $tpl = Renderer::getMarkupTemplate('acl_selector.tpl');
294                 $o = Renderer::replaceMacros($tpl, [
295                         '$showall' => L10n::t('Visible to everybody'),
296                         '$show' => L10n::t('show'),
297                         '$hide' => L10n::t('don\'t show'),
298                         '$allowcid' => json_encode(defaults($default_permissions, 'allow_cid', '')),
299                         '$allowgid' => json_encode(defaults($default_permissions, 'allow_gid', '')),
300                         '$denycid' => json_encode(defaults($default_permissions, 'deny_cid', '')),
301                         '$denygid' => json_encode(defaults($default_permissions, 'deny_gid', '')),
302                         '$networks' => $show_jotnets,
303                         '$emailcc' => L10n::t('CC: email addresses'),
304                         '$emtitle' => L10n::t('Example: bob@example.com, mary@example.com'),
305                         '$jotnets' => $jotnets,
306                         '$aclModalTitle' => L10n::t('Permissions'),
307                         '$aclModalDismiss' => L10n::t('Close'),
308                         '$features' => [
309                                 'aclautomention' => Feature::isEnabled($user['uid'], 'aclautomention') ? 'true' : 'false'
310                         ],
311                 ]);
312
313                 return $o;
314         }
315
316         /**
317          * Searching for global contacts for autocompletion
318          *
319          * @brief Searching for global contacts for autocompletion
320          * @param string $search Name or part of a name or nick
321          * @param string $mode   Search mode (e.g. "community")
322          * @return array with the search results
323          */
324         public static function contactAutocomplete($search, $mode)
325         {
326                 if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
327                         return [];
328                 }
329
330                 // don't search if search term has less than 2 characters
331                 if (!$search || mb_strlen($search) < 2) {
332                         return [];
333                 }
334
335                 if (substr($search, 0, 1) === '@') {
336                         $search = substr($search, 1);
337                 }
338
339                 // check if searching in the local global contact table is enabled
340                 if (Config::get('system', 'poco_local_search')) {
341                         $return = GContact::searchByName($search, $mode);
342                 } else {
343                         $p = defaults($_GET, 'page', 1) != 1 ? '&p=' . defaults($_GET, 'page', 1) : '';
344
345                         $curlResult = Network::curl(get_server() . '/lsearch?f=' . $p . '&search=' . urlencode($search));
346                         if ($curlResult->isSuccess()) {
347                                 $lsearch = json_decode($curlResult->getBody(), true);
348                                 if (!empty($lsearch['results'])) {
349                                         $return = $lsearch['results'];
350                                 }
351                         }
352                 }
353
354                 return defaults($return, []);
355         }
356 }