]> git.mxchange.org Git - friendica.git/blob - src/Core/ACL.php
Rename dbesc to DBA::escape
[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 <mrpetovan@gmail.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 = [NETWORK_DFRN];
50                                 break;
51                         case 'PRIVATE':
52                                 if (!empty($a->user['prvnets'])) {
53                                         $networks = [NETWORK_DFRN, NETWORK_MAIL, NETWORK_DIASPORA];
54                                 } else {
55                                         $networks = [NETWORK_DFRN, NETWORK_FACEBOOK, NETWORK_MAIL, NETWORK_DIASPORA];
56                                 }
57                                 break;
58                         case 'TWO_WAY':
59                                 if (!empty($a->user['prvnets'])) {
60                                         $networks = [NETWORK_DFRN, NETWORK_MAIL, NETWORK_DIASPORA];
61                                 } else {
62                                         $networks = [NETWORK_DFRN, NETWORK_FACEBOOK, NETWORK_MAIL, NETWORK_DIASPORA, NETWORK_OSTATUS];
63                                 }
64                                 break;
65                         default: /// @TODO Maybe log this call?
66                                 break;
67                 }
68
69                 $x = ['options' => $options, 'size' => $size, 'single' => $single, 'mutual' => $mutual, 'exclude' => $exclude, 'networks' => $networks];
70
71                 Addon::callHooks('contact_select_options', $x);
72
73                 $o = '';
74
75                 $sql_extra = '';
76
77                 if (!empty($x['mutual'])) {
78                         $sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
79                 }
80
81                 if (!empty($x['exclude'])) {
82                         $sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude']));
83                 }
84
85                 if (!empty($x['networks'])) {
86                         /// @TODO rewrite to foreach()
87                         array_walk($x['networks'], function (&$value) {
88                                 $value = "'" . DBA::escape($value) . "'";
89                         });
90                         $str_nets = implode(',', $x['networks']);
91                         $sql_extra .= " AND `network` IN ( $str_nets ) ";
92                 }
93
94                 $tabindex = (!empty($options['tabindex']) ? 'tabindex="' . $options["tabindex"] . '"' : '');
95
96                 if (!empty($x['single'])) {
97                         $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"" . $x['size'] . "\" $tabindex >\r\n";
98                 } else {
99                         $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"" . $x['size'] . "$\" $tabindex >\r\n";
100                 }
101
102                 $stmt = DBA::p("SELECT `id`, `name`, `url`, `network` FROM `contact`
103                         WHERE `uid` = ? AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
104                         $sql_extra
105                         ORDER BY `name` ASC ", intval(local_user())
106                 );
107
108                 $contacts = DBA::toArray($stmt);
109
110                 $arr = ['contact' => $contacts, 'entry' => $o];
111
112                 // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
113                 Addon::callHooks($a->module . '_pre_' . $selname, $arr);
114
115                 if (DBA::isResult($contacts)) {
116                         foreach ($contacts as $contact) {
117                                 if (in_array($contact['id'], $preselected)) {
118                                         $selected = ' selected="selected" ';
119                                 } else {
120                                         $selected = '';
121                                 }
122
123                                 $trimmed = mb_substr($contact['name'], 0, 20);
124
125                                 $o .= "<option value=\"{$contact['id']}\" $selected title=\"{$contact['name']}|{$contact['url']}\" >$trimmed</option>\r\n";
126                         }
127                 }
128
129                 $o .= '</select>' . PHP_EOL;
130
131                 Addon::callHooks($a->module . '_post_' . $selname, $o);
132
133                 return $o;
134         }
135
136         /**
137          * Returns a select input tag with all the contact of the local user
138          *
139          * @param string $selname     Name attribute of the select input tag
140          * @param string $selclass    Class attribute of the select input tag
141          * @param array  $preselected Contact IDs that should be already selected
142          * @param int    $size        Length of the select box
143          * @param int    $tabindex    Select input tag tabindex attribute
144          * @return string
145          */
146         public static function getMessageContactSelectHTML($selname, $selclass, array $preselected = [], $size = 4, $tabindex = null)
147         {
148                 $a = self::getApp();
149
150                 $o = '';
151
152                 // When used for private messages, we limit correspondence to mutual DFRN/Friendica friends and the selector
153                 // to one recipient. By default our selector allows multiple selects amongst all contacts.
154                 $sql_extra = sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
155                 $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ", NETWORK_DFRN, NETWORK_DIASPORA);
156
157                 $tabindex_attr = !empty($tabindex) ? ' tabindex="' . intval($tabindex) . '"' : '';
158
159                 $hidepreselected = '';
160                 if ($preselected) {
161                         $sql_extra .= " AND `id` IN (" . implode(",", $preselected) . ")";
162                         $hidepreselected = ' style="display: none;"';
163                 }
164
165                 $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\"$tabindex_attr$hidepreselected>\r\n";
166
167                 $stmt = DBA::p("SELECT `id`, `name`, `url`, `network` FROM `contact`
168                         WHERE `uid` = ? AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
169                         $sql_extra
170                         ORDER BY `name` ASC ", intval(local_user())
171                 );
172
173                 $contacts = DBA::toArray($stmt);
174
175                 $arr = ['contact' => $contacts, 'entry' => $o];
176
177                 // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
178                 Addon::callHooks($a->module . '_pre_' . $selname, $arr);
179
180                 $receiverlist = [];
181
182                 if (DBA::isResult($contacts)) {
183                         foreach ($contacts as $contact) {
184                                 if (in_array($contact['id'], $preselected)) {
185                                         $selected = ' selected="selected"';
186                                 } else {
187                                         $selected = '';
188                                 }
189
190                                 $trimmed = Protocol::formatMention($contact['url'], $contact['name']);
191
192                                 $receiverlist[] = $trimmed;
193
194                                 $o .= "<option value=\"{$contact['id']}\"$selected title=\"{$contact['name']}|{$contact['url']}\" >$trimmed</option>\r\n";
195                         }
196                 }
197
198                 $o .= '</select>' . PHP_EOL;
199
200                 if ($preselected) {
201                         $o .= implode(', ', $receiverlist);
202                 }
203
204                 Addon::callHooks($a->module . '_post_' . $selname, $o);
205
206                 return $o;
207         }
208
209         private static function fixACL(&$item)
210         {
211                 $item = intval(str_replace(['<', '>'], ['', ''], $item));
212         }
213
214         /**
215          * Return the default permission of the provided user array
216          *
217          * @param array $user
218          * @return array Hash of contact id lists
219          */
220         public static function getDefaultUserPermissions(array $user = null)
221         {
222                 $matches = [];
223
224                 $acl_regex = '/<([0-9]+)>/i';
225
226                 preg_match_all($acl_regex, defaults($user, 'allow_cid', ''), $matches);
227                 $allow_cid = $matches[1];
228                 preg_match_all($acl_regex, defaults($user, 'allow_gid', ''), $matches);
229                 $allow_gid = $matches[1];
230                 preg_match_all($acl_regex, defaults($user, 'deny_cid', ''), $matches);
231                 $deny_cid = $matches[1];
232                 preg_match_all($acl_regex, defaults($user, 'deny_gid', ''), $matches);
233                 $deny_gid = $matches[1];
234
235                 // Reformats the ACL data so that it is accepted by the JS frontend
236                 array_walk($allow_cid, 'self::fixACL');
237                 array_walk($allow_gid, 'self::fixACL');
238                 array_walk($deny_cid, 'self::fixACL');
239                 array_walk($deny_gid, 'self::fixACL');
240
241                 Contact::pruneUnavailable($allow_cid);
242
243                 return [
244                         'allow_cid' => $allow_cid,
245                         'allow_gid' => $allow_gid,
246                         'deny_cid' => $deny_cid,
247                         'deny_gid' => $deny_gid,
248                 ];
249         }
250
251         /**
252          * Return the full jot ACL selector HTML
253          *
254          * @param array $user
255          * @param bool  $show_jotnets
256          * @return string
257          */
258         public static function getFullSelectorHTML(array $user = null, $show_jotnets = false)
259         {
260
261                 if (empty($user['uid'])) {
262                         return '';
263                 }
264
265                 $perms = self::getDefaultUserPermissions($user);
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($user['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 = get_markup_template('acl_selector.tpl');
296                 $o = replace_macros($tpl, [
297                         '$showall' => L10n::t('Visible to everybody'),
298                         '$show' => L10n::t('show'),
299                         '$hide' => L10n::t('don\'t show'),
300                         '$allowcid' => json_encode($perms['allow_cid']),
301                         '$allowgid' => json_encode($perms['allow_gid']),
302                         '$denycid' => json_encode($perms['deny_cid']),
303                         '$denygid' => json_encode($perms['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                         $a = self::getApp();
346                         $p = $a->pager['page'] != 1 ? '&p=' . $a->pager['page'] : '';
347
348                         $response = Network::curl(get_server() . '/lsearch?f=' . $p . '&search=' . urlencode($search));
349                         if ($response['success']) {
350                                 $lsearch = json_decode($response['body'], true);
351                                 if (!empty($lsearch['results'])) {
352                                         $return = $lsearch['results'];
353                                 }
354                         }
355                 }
356
357                 return defaults($return, []);
358         }
359 }