]> git.mxchange.org Git - friendica.git/blob - src/Core/ACL.php
78d2ca41bf23f474479bcb4b14fc466f50bb177a
[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                 $item = intval(str_replace(['<', '>'], ['', ''], $item));
226         }
227
228         /**
229          * Return the default permission of the provided user array
230          *
231          * @param array $user
232          * @return array Hash of contact id lists
233          */
234         public static function getDefaultUserPermissions(array $user = null)
235         {
236                 $matches = [];
237
238                 $acl_regex = '/<([0-9]+)>/i';
239
240                 preg_match_all($acl_regex, defaults($user, 'allow_cid', ''), $matches);
241                 $allow_cid = $matches[1];
242                 preg_match_all($acl_regex, defaults($user, 'allow_gid', ''), $matches);
243                 $allow_gid = $matches[1];
244                 preg_match_all($acl_regex, defaults($user, 'deny_cid', ''), $matches);
245                 $deny_cid = $matches[1];
246                 preg_match_all($acl_regex, defaults($user, 'deny_gid', ''), $matches);
247                 $deny_gid = $matches[1];
248
249                 // Reformats the ACL data so that it is accepted by the JS frontend
250                 array_walk($allow_cid, 'self::fixACL');
251                 array_walk($allow_gid, 'self::fixACL');
252                 array_walk($deny_cid, 'self::fixACL');
253                 array_walk($deny_gid, 'self::fixACL');
254
255                 Contact::pruneUnavailable($allow_cid);
256
257                 return [
258                         'allow_cid' => $allow_cid,
259                         'allow_gid' => $allow_gid,
260                         'deny_cid' => $deny_cid,
261                         'deny_gid' => $deny_gid,
262                 ];
263         }
264
265         /**
266          * Return the full jot ACL selector HTML
267          *
268          * @param array $user
269          * @param bool  $show_jotnets
270          * @return string
271          */
272         public static function getFullSelectorHTML(array $user = null, $show_jotnets = false)
273         {
274                 $perms = self::getDefaultUserPermissions($user);
275
276                 $jotnets = '';
277                 if ($show_jotnets) {
278                         $imap_disabled = !function_exists('imap_open') || Config::get('system', 'imap_disabled');
279
280                         $mail_enabled = false;
281                         $pubmail_enabled = false;
282
283                         if (!$imap_disabled) {
284                                 $mailacct = dba::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', local_user()]);
285                                 if (DBM::is_result($mailacct)) {
286                                         $mail_enabled = true;
287                                         $pubmail_enabled = !empty($mailacct['pubmail']);
288                                 }
289                         }
290
291                         if (empty($user['hidewall'])) {
292                                 if ($mail_enabled) {
293                                         $selected = $pubmail_enabled ? ' checked="checked"' : '';
294                                         $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . L10n::t("Post to Email") . '</div>';
295                                 }
296
297                                 Addon::callHooks('jot_networks', $jotnets);
298                         } else {
299                                 $jotnets .= L10n::t('Connectors disabled, since "%s" is enabled.',
300                                                 L10n::t('Hide your profile details from unknown viewers?'));
301                         }
302                 }
303
304                 $tpl = get_markup_template('acl_selector.tpl');
305                 $o = replace_macros($tpl, [
306                         '$showall' => L10n::t('Visible to everybody'),
307                         '$show' => L10n::t('show'),
308                         '$hide' => L10n::t('don\'t show'),
309                         '$allowcid' => json_encode($perms['allow_cid']),
310                         '$allowgid' => json_encode($perms['allow_gid']),
311                         '$denycid' => json_encode($perms['deny_cid']),
312                         '$denygid' => json_encode($perms['deny_gid']),
313                         '$networks' => $show_jotnets,
314                         '$emailcc' => L10n::t('CC: email addresses'),
315                         '$emtitle' => L10n::t('Example: bob@example.com, mary@example.com'),
316                         '$jotnets' => $jotnets,
317                         '$aclModalTitle' => L10n::t('Permissions'),
318                         '$aclModalDismiss' => L10n::t('Close'),
319                         '$features' => [
320                                 'aclautomention' => Feature::isEnabled($user['uid'], 'aclautomention') ? 'true' : 'false'
321                         ],
322                 ]);
323
324                 return $o;
325         }
326
327         /**
328          * Searching for global contacts for autocompletion
329          *
330          * @brief Searching for global contacts for autocompletion
331          * @param string $search Name or part of a name or nick
332          * @param string $mode   Search mode (e.g. "community")
333          * @return array with the search results
334          */
335         public static function contactAutocomplete($search, $mode)
336         {
337                 if ((Config::get('system', 'block_public')) && (!local_user()) && (!remote_user())) {
338                         return [];
339                 }
340
341                 // don't search if search term has less than 2 characters
342                 if (!$search || mb_strlen($search) < 2) {
343                         return [];
344                 }
345
346                 if (substr($search, 0, 1) === '@') {
347                         $search = substr($search, 1);
348                 }
349
350                 // check if searching in the local global contact table is enabled
351                 if (Config::get('system', 'poco_local_search')) {
352                         $return = GContact::searchByName($search, $mode);
353                 } else {
354                         $a = self::getApp();
355                         $p = $a->pager['page'] != 1 ? '&p=' . $a->pager['page'] : '';
356
357                         $response = Network::curl(get_server() . '/lsearch?f=' . $p . '&search=' . urlencode($search));
358                         if ($response['success']) {
359                                 $lsearch = json_decode($response['body'], true);
360                                 if (!empty($lsearch['results'])) {
361                                         $return = $lsearch['results'];
362                                 }
363                         }
364                 }
365
366                 return defaults($return, []);
367         }
368 }