]> git.mxchange.org Git - friendica.git/blob - src/Core/ACL.php
Don't show deleted contacts, set new AP contacts as "pending" until they are accepted
[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\Core\Protocol;
12 use Friendica\Core\Renderer;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\GContact;
16 use Friendica\Util\Network;
17
18 /**
19  * Handle ACL management and display
20  *
21  * @author Hypolite Petovan <hypolite@mrpetovan.com>
22  */
23 class ACL extends BaseObject
24 {
25         /**
26          * Returns a select input tag with all the contact of the local user
27          *
28          * @param string $selname Name attribute of the select input tag
29          * @param string $selclass Class attribute of the select input tag
30          * @param array $options Available options:
31          * - size: length of the select box
32          * - mutual_friends: Only used for the hook
33          * - single: Only used for the hook
34          * - exclude: Only used for the hook
35          * @param array $preselected Contact ID that should be already selected
36          * @return string
37          */
38         public static function getSuggestContactSelectHTML($selname, $selclass, array $options = [], array $preselected = [])
39         {
40                 $a = self::getApp();
41
42                 $networks = null;
43
44                 $size = defaults($options, 'size', 4);
45                 $mutual = !empty($options['mutual_friends']);
46                 $single = !empty($options['single']) && empty($options['multiple']);
47                 $exclude = defaults($options, 'exclude', false);
48
49                 switch (defaults($options, 'networks', Protocol::PHANTOM)) {
50                         case 'DFRN_ONLY':
51                                 $networks = [Protocol::DFRN];
52                                 break;
53
54                         case 'PRIVATE':
55                                 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::MAIL, Protocol::DIASPORA];
56                                 break;
57
58                         case 'TWO_WAY':
59                                 if (!empty($a->user['prvnets'])) {
60                                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::MAIL, Protocol::DIASPORA];
61                                 } else {
62                                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::MAIL, Protocol::DIASPORA, Protocol::OSTATUS];
63                                 }
64                                 break;
65
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::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 = "'" . DBA::escape($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 NOT `deleted` AND `notify` != ''
105                         $sql_extra
106                         ORDER BY `name` ASC ", intval(local_user())
107                 );
108
109                 $contacts = DBA::toArray($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 (DBA::isResult($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::FRIEND));
156                 $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ", Protocol::DFRN, Protocol::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 NOT `deleted` AND `notify` != ''
170                         $sql_extra
171                         ORDER BY `name` ASC ", intval(local_user())
172                 );
173
174                 $contacts = DBA::toArray($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 (DBA::isResult($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                User array
256          * @param array $default_permissions Static defaults permission array: ['allow_cid' => '', 'allow_gid' => '', 'deny_cid' => '', 'deny_gid' => '']
257          * @param bool  $show_jotnets
258          * @return string
259          */
260         public static function getFullSelectorHTML(array $user, $show_jotnets = false, array $default_permissions = [])
261         {
262                 // Defaults user permissions
263                 if (empty($default_permissions)) {
264                         $default_permissions = self::getDefaultUserPermissions($user);
265                 }
266
267                 $jotnets = '';
268                 if ($show_jotnets) {
269                         $imap_disabled = !function_exists('imap_open') || Config::get('system', 'imap_disabled');
270
271                         $mail_enabled = false;
272                         $pubmail_enabled = false;
273
274                         if (!$imap_disabled) {
275                                 $mailacct = DBA::selectFirst('mailacct', ['pubmail'], ['`uid` = ? AND `server` != ""', local_user()]);
276                                 if (DBA::isResult($mailacct)) {
277                                         $mail_enabled = true;
278                                         $pubmail_enabled = !empty($mailacct['pubmail']);
279                                 }
280                         }
281
282                         if (empty($default_permissions['hidewall'])) {
283                                 if ($mail_enabled) {
284                                         $selected = $pubmail_enabled ? ' checked="checked"' : '';
285                                         $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . L10n::t("Post to Email") . '</div>';
286                                 }
287
288                                 Addon::callHooks('jot_networks', $jotnets);
289                         } else {
290                                 $jotnets .= L10n::t('Connectors disabled, since "%s" is enabled.',
291                                                 L10n::t('Hide your profile details from unknown viewers?'));
292                         }
293                 }
294
295                 $tpl = Renderer::getMarkupTemplate('acl_selector.tpl');
296                 $o = Renderer::replaceMacros($tpl, [
297                         '$showall' => L10n::t('Visible to everybody'),
298                         '$show' => L10n::t('show'),
299                         '$hide' => L10n::t('don\'t show'),
300                         '$allowcid' => json_encode(defaults($default_permissions, 'allow_cid', '')),
301                         '$allowgid' => json_encode(defaults($default_permissions, 'allow_gid', '')),
302                         '$denycid' => json_encode(defaults($default_permissions, 'deny_cid', '')),
303                         '$denygid' => json_encode(defaults($default_permissions, 'deny_gid', '')),
304                         '$networks' => $show_jotnets,
305                         '$emailcc' => L10n::t('CC: email addresses'),
306                         '$emtitle' => L10n::t('Example: bob@example.com, mary@example.com'),
307                         '$jotnets' => $jotnets,
308                         '$aclModalTitle' => L10n::t('Permissions'),
309                         '$aclModalDismiss' => L10n::t('Close'),
310                         '$features' => [
311                                 'aclautomention' => Feature::isEnabled($user['uid'], 'aclautomention') ? 'true' : 'false'
312                         ],
313                 ]);
314
315                 return $o;
316         }
317
318         /**
319          * Searching for global contacts for autocompletion
320          *
321          * @brief Searching for global contacts for autocompletion
322          * @param string $search Name or part of a name or nick
323          * @param string $mode   Search mode (e.g. "community")
324          * @return array with the search results
325          */
326         public static function contactAutocomplete($search, $mode)
327         {
328                 if (Config::get('system', 'block_public') && !local_user() && !remote_user()) {
329                         return [];
330                 }
331
332                 // don't search if search term has less than 2 characters
333                 if (!$search || mb_strlen($search) < 2) {
334                         return [];
335                 }
336
337                 if (substr($search, 0, 1) === '@') {
338                         $search = substr($search, 1);
339                 }
340
341                 // check if searching in the local global contact table is enabled
342                 if (Config::get('system', 'poco_local_search')) {
343                         $return = GContact::searchByName($search, $mode);
344                 } else {
345                         $p = defaults($_GET, 'page', 1) != 1 ? '&p=' . defaults($_GET, 'page', 1) : '';
346
347                         $curlResult = Network::curl(get_server() . '/lsearch?f=' . $p . '&search=' . urlencode($search));
348                         if ($curlResult->isSuccess()) {
349                                 $lsearch = json_decode($curlResult->getBody(), true);
350                                 if (!empty($lsearch['results'])) {
351                                         $return = $lsearch['results'];
352                                 }
353                         }
354                 }
355
356                 return defaults($return, []);
357         }
358 }