]> git.mxchange.org Git - friendica.git/blob - include/acl_selectors.php
Class file relocations
[friendica.git] / include / acl_selectors.php
1 <?php
2
3 /**
4  * @file include/acl_selectors.php
5  */
6
7 use Friendica\App;
8 use Friendica\Core\Config;
9 use Friendica\Database\DBM;
10
11 require_once "include/contact_selectors.php";
12 require_once "include/contact_widgets.php";
13 require_once "include/DirSearch.php";
14 require_once "include/features.php";
15 require_once "mod/proxy.php";
16
17
18 /**
19  * @package acl_selectors
20  */
21 function group_select($selname,$selclass,$preselected = false,$size = 4) {
22
23         $a = get_app();
24
25         $o = '';
26
27         $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"$size\" >\r\n";
28
29         $r = q("SELECT `id`, `name` FROM `group` WHERE NOT `deleted` AND `uid` = %d ORDER BY `name` ASC",
30                 intval(local_user())
31         );
32
33
34         $arr = array('group' => $r, 'entry' => $o);
35
36         // e.g. 'network_pre_group_deny', 'profile_pre_group_allow'
37
38         call_hooks($a->module . '_pre_' . $selname, $arr);
39
40         if (DBM::is_result($r)) {
41                 foreach ($r as $rr) {
42                         if ((is_array($preselected)) && in_array($rr['id'], $preselected)) {
43                                 $selected = " selected=\"selected\" ";
44                         } else {
45                                 $selected = '';
46                         }
47
48                         $trimmed = mb_substr($rr['name'],0,12);
49
50                         $o .= "<option value=\"{$rr['id']}\" $selected title=\"{$rr['name']}\" >$trimmed</option>\r\n";
51                 }
52
53         }
54         $o .= "</select>\r\n";
55
56         call_hooks($a->module . '_post_' . $selname, $o);
57
58
59         return $o;
60 }
61
62 /// @TODO after an optional parameter, no mandadory parameter can follow
63 /// @TODO find proper type-hints
64 function contact_selector($selname, $selclass, $preselected = false, $options) {
65
66         $a = get_app();
67
68         $mutual = false;
69         $networks = null;
70         $single = false;
71         $exclude = false;
72         $size = 4;
73
74         if (is_array($options)) {
75                 if (x($options, 'size'))
76                         $size = $options['size'];
77
78                 if (x($options, 'mutual_friends')) {
79                         $mutual = true;
80                 }
81                 if (x($options, 'single')) {
82                         $single = true;
83                 }
84                 if (x($options, 'multiple')) {
85                         $single = false;
86                 }
87                 if (x($options, 'exclude')) {
88                         $exclude = $options['exclude'];
89                 }
90
91                 if (x($options, 'networks')) {
92                         switch ($options['networks']) {
93                                 case 'DFRN_ONLY':
94                                         $networks = array(NETWORK_DFRN);
95                                         break;
96                                 case 'PRIVATE':
97                                         if (is_array($a->user) && $a->user['prvnets']) {
98                                                 $networks = array(NETWORK_DFRN, NETWORK_MAIL, NETWORK_DIASPORA);
99                                         } else {
100                                                 $networks = array(NETWORK_DFRN, NETWORK_FACEBOOK, NETWORK_MAIL, NETWORK_DIASPORA);
101                                         }
102                                         break;
103                                 case 'TWO_WAY':
104                                         if (is_array($a->user) && $a->user['prvnets']) {
105                                                 $networks = array(NETWORK_DFRN, NETWORK_MAIL, NETWORK_DIASPORA);
106                                         } else {
107                                                 $networks = array(NETWORK_DFRN, NETWORK_FACEBOOK, NETWORK_MAIL, NETWORK_DIASPORA, NETWORK_OSTATUS);
108                                         }
109                                         break;
110                                 default: /// @TODO Maybe log this call?
111                                         break;
112                         }
113                 }
114         }
115
116         $x = array('options' => $options, 'size' => $size, 'single' => $single, 'mutual' => $mutual, 'exclude' => $exclude, 'networks' => $networks);
117
118         call_hooks('contact_select_options', $x);
119
120         $o = '';
121
122         $sql_extra = '';
123
124         if (x($x, 'mutual')) {
125                 $sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
126         }
127
128         if (x($x, 'exclude')) {
129                 $sql_extra .= sprintf(" AND `id` != %d ", intval($x['exclude']));
130         }
131
132         if (is_array($x['networks']) && count($x['networks'])) {
133                 /// @TODO rewrite to foreach()
134                 for ($y = 0; $y < count($x['networks']) ; $y ++) {
135                         $x['networks'][$y] = "'" . dbesc($x['networks'][$y]) . "'";
136                 }
137                 $str_nets = implode(',', $x['networks']);
138                 $sql_extra .= " AND `network` IN ( $str_nets ) ";
139         }
140
141         $tabindex = (x($options, 'tabindex') ? "tabindex=\"" . $options["tabindex"] . "\"" : "");
142
143         if ($x['single']) {
144                 $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"" . $x['size'] . "\" $tabindex >\r\n";
145         } else {
146                 $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"" . $x['size'] . "$\" $tabindex >\r\n";
147         }
148
149         $r = q("SELECT `id`, `name`, `url`, `network` FROM `contact`
150                 WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
151                 $sql_extra
152                 ORDER BY `name` ASC ",
153                 intval(local_user())
154         );
155
156
157         $arr = array('contact' => $r, 'entry' => $o);
158
159         // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
160
161         call_hooks($a->module . '_pre_' . $selname, $arr);
162
163         if (DBM::is_result($r)) {
164                 foreach ($r as $rr) {
165                         if ((is_array($preselected)) && in_array($rr['id'], $preselected)) {
166                                 $selected = " selected=\"selected\" ";
167                         } else {
168                                 $selected = '';
169                         }
170
171                         $trimmed = mb_substr($rr['name'],0,20);
172
173                         $o .= "<option value=\"{$rr['id']}\" $selected title=\"{$rr['name']}|{$rr['url']}\" >$trimmed</option>\r\n";
174                 }
175
176         }
177
178         $o .= "</select>\r\n";
179
180         call_hooks($a->module . '_post_' . $selname, $o);
181
182         return $o;
183 }
184
185
186
187 function contact_select($selname, $selclass, $preselected = false, $size = 4, $privmail = false, $celeb = false, $privatenet = false, $tabindex = null) {
188
189         require_once "include/bbcode.php";
190
191         $a = get_app();
192
193         $o = '';
194
195         // When used for private messages, we limit correspondence to mutual DFRN/Friendica friends and the selector
196         // to one recipient. By default our selector allows multiple selects amongst all contacts.
197
198         $sql_extra = '';
199
200         if ($privmail || $celeb) {
201                 $sql_extra .= sprintf(" AND `rel` = %d ", intval(CONTACT_IS_FRIEND));
202         }
203
204         if ($privmail) {
205                 $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s') ",
206                                         NETWORK_DFRN, NETWORK_DIASPORA);
207         } elseif ($privatenet) {
208                 $sql_extra .= sprintf(" AND `network` IN ('%s' , '%s', '%s', '%s') ",
209                                         NETWORK_DFRN, NETWORK_MAIL, NETWORK_FACEBOOK, NETWORK_DIASPORA);
210         }
211
212         $tabindex = ($tabindex > 0 ? "tabindex=\"$tabindex\"" : "");
213
214         if ($privmail && $preselected) {
215                 $sql_extra .= " AND `id` IN (".implode(",", $preselected).")";
216                 $hidepreselected = ' style="display: none;"';
217         } else {
218                 $hidepreselected = "";
219         }
220
221         if ($privmail) {
222                 $o .= "<select name=\"$selname\" id=\"$selclass\" class=\"$selclass\" size=\"$size\" $tabindex $hidepreselected>\r\n";
223         } else {
224                 $o .= "<select name=\"{$selname}[]\" id=\"$selclass\" class=\"$selclass\" multiple=\"multiple\" size=\"$size\" $tabindex >\r\n";
225         }
226
227         $r = q("SELECT `id`, `name`, `url`, `network` FROM `contact`
228                 WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
229                 $sql_extra
230                 ORDER BY `name` ASC ",
231                 intval(local_user())
232         );
233
234
235         $arr = array('contact' => $r, 'entry' => $o);
236
237         // e.g. 'network_pre_contact_deny', 'profile_pre_contact_allow'
238
239         call_hooks($a->module . '_pre_' . $selname, $arr);
240
241         $receiverlist = array();
242
243         if (DBM::is_result($r)) {
244                 foreach ($r as $rr) {
245                         if ((is_array($preselected)) && in_array($rr['id'], $preselected)) {
246                                 $selected = " selected=\"selected\" ";
247                         } else {
248                                 $selected = '';
249                         }
250
251                         if ($privmail) {
252                                 $trimmed = GetProfileUsername($rr['url'], $rr['name'], false);
253                         } else {
254                                 $trimmed = mb_substr($rr['name'],0,20);
255                         }
256
257                         $receiverlist[] = $trimmed;
258
259                         $o .= "<option value=\"{$rr['id']}\" $selected title=\"{$rr['name']}|{$rr['url']}\" >$trimmed</option>\r\n";
260                 }
261
262         }
263
264         $o .= "</select>\r\n";
265
266         if ($privmail && $preselected) {
267                 $o .= implode(", ", $receiverlist);
268         }
269
270         call_hooks($a->module . '_post_' . $selname, $o);
271
272         return $o;
273 }
274
275
276 function fixacl(&$item) {
277         $item = intval(str_replace(array('<', '>'), array('', ''), $item));
278 }
279
280 function prune_deadguys($arr) {
281
282         if (! $arr) {
283                 return $arr;
284         }
285
286         $str = dbesc(implode(',', $arr));
287
288         $r = q("SELECT `id` FROM `contact` WHERE `id` IN ( " . $str . ") AND `blocked` = 0 AND `pending` = 0 AND `archive` = 0 ");
289
290         if (DBM::is_result($r)) {
291                 $ret = array();
292                 foreach ($r as $rr) {
293                         $ret[] = intval($rr['id']);
294                 }
295                 return $ret;
296         }
297
298         return array();
299 }
300
301
302 function get_acl_permissions($user = null) {
303         $allow_cid = $allow_gid = $deny_cid = $deny_gid = false;
304
305         if (is_array($user)) {
306                 $allow_cid = ((strlen($user['allow_cid']))
307                         ? explode('><', $user['allow_cid']) : array() );
308                 $allow_gid = ((strlen($user['allow_gid']))
309                         ? explode('><', $user['allow_gid']) : array() );
310                 $deny_cid  = ((strlen($user['deny_cid']))
311                         ? explode('><', $user['deny_cid']) : array() );
312                 $deny_gid  = ((strlen($user['deny_gid']))
313                         ? explode('><', $user['deny_gid']) : array() );
314                 array_walk($allow_cid,'fixacl');
315                 array_walk($allow_gid,'fixacl');
316                 array_walk($deny_cid,'fixacl');
317                 array_walk($deny_gid,'fixacl');
318         }
319
320         $allow_cid = prune_deadguys($allow_cid);
321
322         return array(
323                 'allow_cid' => $allow_cid,
324                 'allow_gid' => $allow_gid,
325                 'deny_cid' => $deny_cid,
326                 'deny_gid' => $deny_gid,
327         );
328 }
329
330
331 function populate_acl($user = null, $show_jotnets = false) {
332
333         $perms = get_acl_permissions($user);
334
335         $jotnets = '';
336         if ($show_jotnets) {
337                 $mail_disabled = ((function_exists('imap_open') && (! Config::get('system','imap_disabled'))) ? 0 : 1);
338
339                 $mail_enabled = false;
340                 $pubmail_enabled = false;
341
342                 if (! $mail_disabled) {
343                         $r = q("SELECT `pubmail` FROM `mailacct` WHERE `uid` = %d AND `server` != '' LIMIT 1",
344                                 intval(local_user())
345                         );
346                         if (DBM::is_result($r)) {
347                                 $mail_enabled = true;
348                                 if (intval($r[0]['pubmail'])) {
349                                         $pubmail_enabled = true;
350                                 }
351                         }
352                 }
353
354                 if (!$user['hidewall']) {
355                         if ($mail_enabled) {
356                                 $selected = (($pubmail_enabled) ? ' checked="checked" ' : '');
357                                 $jotnets .= '<div class="profile-jot-net"><input type="checkbox" name="pubmail_enable"' . $selected . ' value="1" /> ' . t("Post to Email") . '</div>';
358                         }
359
360                         call_hooks('jot_networks', $jotnets);
361                 } else {
362                         $jotnets .= sprintf(t('Connectors disabled, since "%s" is enabled.'),
363                                             t('Hide your profile details from unknown viewers?'));
364                 }
365         }
366
367         $tpl = get_markup_template("acl_selector.tpl");
368         $o = replace_macros($tpl, array(
369                 '$showall'=> t("Visible to everybody"),
370                 '$show' => t("show"),
371                 '$hide'  => t("don't show"),
372                 '$allowcid' => json_encode($perms['allow_cid']),
373                 '$allowgid' => json_encode($perms['allow_gid']),
374                 '$denycid' => json_encode($perms['deny_cid']),
375                 '$denygid' => json_encode($perms['deny_gid']),
376                 '$networks' => $show_jotnets,
377                 '$emailcc' => t('CC: email addresses'),
378                 '$emtitle' => t('Example: bob@example.com, mary@example.com'),
379                 '$jotnets' => $jotnets,
380                 '$aclModalTitle' => t('Permissions'),
381                 '$aclModalDismiss' => t('Close'),
382                 '$features' => array(
383                 'aclautomention' => (feature_enabled($user['uid'], "aclautomention") ? "true" : "false")
384                 ),
385         ));
386
387
388         return $o;
389
390 }
391
392 function construct_acl_data(App $a, $user) {
393         // This function is now deactivated. It seems as if the generated data isn't used anywhere.
394         /// @todo Remove this function and all function calls before releasing Friendica 3.5.3
395         return;
396
397         // Get group and contact information for html ACL selector
398         $acl_data = acl_lookup($a, 'html');
399
400         $user_defaults = get_acl_permissions($user);
401
402         if ($acl_data['groups']) {
403                 foreach ($acl_data['groups'] as $key => $group) {
404                         // Add a "selected" flag to groups that are posted to by default
405                         if ($user_defaults['allow_gid'] &&
406                                         in_array($group['id'], $user_defaults['allow_gid']) && !in_array($group['id'], $user_defaults['deny_gid']) ) {
407                                 $acl_data['groups'][$key]['selected'] = 1;
408                         } else {
409                                 $acl_data['groups'][$key]['selected'] = 0;
410                         }
411                 }
412         }
413         if ($acl_data['contacts']) {
414                 foreach ($acl_data['contacts'] as $key => $contact) {
415                         // Add a "selected" flag to groups that are posted to by default
416                         if ($user_defaults['allow_cid'] &&
417                                         in_array($contact['id'], $user_defaults['allow_cid']) && !in_array($contact['id'], $user_defaults['deny_cid']) ) {
418                                 $acl_data['contacts'][$key]['selected'] = 1;
419                         } else {
420                                 $acl_data['contacts'][$key]['selected'] = 0;
421                         }
422                 }
423         }
424
425         return $acl_data;
426
427 }
428
429 function acl_lookup(App $a, $out_type = 'json') {
430
431         if (!local_user()) {
432                 return '';
433         }
434
435         $start  =       (x($_REQUEST,'start')           ? $_REQUEST['start']            : 0);
436         $count  =       (x($_REQUEST,'count')           ? $_REQUEST['count']            : 100);
437         $search  =      (x($_REQUEST,'search')          ? $_REQUEST['search']           : "");
438         $type   =       (x($_REQUEST,'type')            ? $_REQUEST['type']             : "");
439         $mode   =       (x($_REQUEST,'smode')           ? $_REQUEST['smode']            : "");
440         $conv_id =      (x($_REQUEST,'conversation')    ? $_REQUEST['conversation']     : null);
441
442         // For use with jquery.textcomplete for private mail completion
443
444         if (x($_REQUEST, 'query') && strlen($_REQUEST['query'])) {
445                 if (! $type) {
446                         $type = 'm';
447                 }
448                 $search = $_REQUEST['query'];
449         }
450
451         logger("Searching for ".$search." - type ".$type, LOGGER_DEBUG);
452
453         if ($search != "") {
454                 $sql_extra = "AND `name` LIKE '%%".dbesc($search)."%%'";
455                 $sql_extra2 = "AND (`attag` LIKE '%%".dbesc($search)."%%' OR `name` LIKE '%%".dbesc($search)."%%' OR `nick` LIKE '%%".dbesc($search)."%%')";
456         } else {
457                 /// @TODO Avoid these needless else blocks by putting variable-initialization atop of if()
458                 $sql_extra = $sql_extra2 = "";
459         }
460
461         // count groups and contacts
462         if ($type == '' || $type == 'g') {
463                 $r = q("SELECT COUNT(*) AS g FROM `group` WHERE `deleted` = 0 AND `uid` = %d $sql_extra",
464                         intval(local_user())
465                 );
466                 $group_count = (int)$r[0]['g'];
467         } else {
468                 $group_count = 0;
469         }
470
471         $sql_extra2 .= " ".unavailable_networks();
472
473         if ($type == '' || $type == 'c') {
474                 // autocomplete for editor mentions
475                 $r = q("SELECT COUNT(*) AS c FROM `contact`
476                                 WHERE `uid` = %d AND NOT `self`
477                                 AND NOT `blocked` AND NOT `pending` AND NOT `archive`
478                                 AND `success_update` >= `failure_update`
479                                 AND `notify` != '' $sql_extra2" ,
480                         intval(local_user())
481                 );
482                 $contact_count = (int)$r[0]['c'];
483         } elseif ($type == 'f') {
484                 // autocomplete for editor mentions of forums
485                 $r = q("SELECT COUNT(*) AS c FROM `contact`
486                                 WHERE `uid` = %d AND NOT `self`
487                                 AND NOT `blocked` AND NOT `pending` AND NOT `archive`
488                                 AND (`forum` OR `prv`)
489                                 AND `success_update` >= `failure_update`
490                                 AND `notify` != '' $sql_extra2" ,
491                         intval(local_user())
492                 );
493                 $contact_count = (int)$r[0]['c'];
494         } elseif ($type == 'm') {
495                 // autocomplete for Private Messages
496
497                 $r = q("SELECT COUNT(*) AS c FROM `contact`
498                                 WHERE `uid` = %d AND NOT `self`
499                                 AND NOT `blocked` AND NOT `pending` AND NOT `archive`
500                                 AND `success_update` >= `failure_update`
501                                 AND `network` IN ('%s','%s','%s') $sql_extra2" ,
502                         intval(local_user()),
503                         dbesc(NETWORK_DFRN),
504                         dbesc(NETWORK_ZOT),
505                         dbesc(NETWORK_DIASPORA)
506                 );
507                 $contact_count = (int)$r[0]['c'];
508
509         } elseif ($type == 'a') {
510
511                 // autocomplete for Contacts
512
513                 $r = q("SELECT COUNT(*) AS c FROM `contact`
514                                 WHERE `uid` = %d AND NOT `self`
515                                 AND NOT `pending` $sql_extra2" ,
516                         intval(local_user())
517                 );
518                 $contact_count = (int)$r[0]['c'];
519
520         } else {
521                 $contact_count = 0;
522         }
523
524
525         $tot = $group_count+$contact_count;
526
527         $groups = array();
528         $contacts = array();
529
530         if ($type == '' || $type == 'g') {
531
532                 /// @todo We should cache this query.
533                 // This can be done when we can delete cache entries via wildcard
534                 $r = q("SELECT `group`.`id`, `group`.`name`, GROUP_CONCAT(DISTINCT `group_member`.`contact-id` SEPARATOR ',') AS uids
535                                 FROM `group`
536                                 INNER JOIN `group_member` ON `group_member`.`gid`=`group`.`id` AND `group_member`.`uid` = `group`.`uid`
537                                 WHERE NOT `group`.`deleted` AND `group`.`uid` = %d
538                                         $sql_extra
539                                 GROUP BY `group`.`name`, `group`.`id`
540                                 ORDER BY `group`.`name`
541                                 LIMIT %d,%d",
542                         intval(local_user()),
543                         intval($start),
544                         intval($count)
545                 );
546
547                 foreach ($r as $g) {
548 //              logger('acl: group: ' . $g['name'] . ' members: ' . $g['uids']);
549                         $groups[] = array(
550                                 "type"  => "g",
551                                 "photo" => "images/twopeople.png",
552                                 "name"  => htmlentities($g['name']),
553                                 "id"    => intval($g['id']),
554                                 "uids"  => array_map("intval", explode(",",$g['uids'])),
555                                 "link"  => '',
556                                 "forum" => '0'
557                         );
558                 }
559                 if ((count($groups) > 0) && ($search == "")) {
560                         $groups[] = array("separator" => true);
561                 }
562         }
563
564         if ($type == '') {
565
566                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv`, (`prv` OR `forum`) AS `frm` FROM `contact`
567                         WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
568                         AND `success_update` >= `failure_update` AND NOT (`network` IN ('%s', '%s'))
569                         $sql_extra2
570                         ORDER BY `name` ASC ",
571                         intval(local_user()),
572                         dbesc(NETWORK_OSTATUS), dbesc(NETWORK_STATUSNET)
573                 );
574         } elseif ($type == 'c') {
575                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
576                         WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
577                         AND `success_update` >= `failure_update` AND NOT (`network` IN ('%s'))
578                         $sql_extra2
579                         ORDER BY `name` ASC ",
580                         intval(local_user()),
581                         dbesc(NETWORK_STATUSNET)
582                 );
583         } elseif ($type == 'f') {
584                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
585                         WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive` AND `notify` != ''
586                         AND `success_update` >= `failure_update` AND NOT (`network` IN ('%s'))
587                         AND (`forum` OR `prv`)
588                         $sql_extra2
589                         ORDER BY `name` ASC ",
590                         intval(local_user()),
591                         dbesc(NETWORK_STATUSNET)
592                 );
593         } elseif ($type == 'm') {
594                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr` FROM `contact`
595                         WHERE `uid` = %d AND NOT `self` AND NOT `blocked` AND NOT `pending` AND NOT `archive`
596                         AND `success_update` >= `failure_update` AND `network` IN ('%s','%s','%s')
597                         $sql_extra2
598                         ORDER BY `name` ASC ",
599                         intval(local_user()),
600                         dbesc(NETWORK_DFRN),
601                         dbesc(NETWORK_ZOT),
602                         dbesc(NETWORK_DIASPORA)
603                 );
604         } elseif ($type == 'a') {
605                 $r = q("SELECT `id`, `name`, `nick`, `micro`, `network`, `url`, `attag`, `addr`, `forum`, `prv` FROM `contact`
606                         WHERE `uid` = %d AND `pending` = 0 AND `success_update` >= `failure_update`
607                         $sql_extra2
608                         ORDER BY `name` ASC ",
609                         intval(local_user())
610                 );
611         } elseif ($type == 'x') {
612                 // autocomplete for global contact search (e.g. navbar search)
613                 $r = navbar_complete($a);
614                 $contacts = array();
615                 if ($r) {
616                         foreach ($r as $g) {
617                                 $contacts[] = array(
618                                         'photo'   => proxy_url($g['photo'], false, PROXY_SIZE_MICRO),
619                                         'name'    => $g['name'],
620                                         'nick'    => (x($g['addr']) ? $g['addr'] : $g['url']),
621                                         'network' => $g['network'],
622                                         'link'    => $g['url'],
623                                         'forum'   => (x($g['community']) ? 1 : 0),
624                                 );
625                         }
626                 }
627                 $o = array(
628                         'start' => $start,
629                         'count' => $count,
630                         'items' => $contacts,
631                 );
632                 echo json_encode($o);
633                 killme();
634         } else {
635                 $r = array();
636         }
637
638
639         if (DBM::is_result($r)) {
640                 $forums = array();
641                 foreach ($r as $g) {
642                         $entry = array(
643                                 'type'    => 'c',
644                                 'photo'   => proxy_url($g['micro'], false, PROXY_SIZE_MICRO),
645                                 'name'    => htmlentities($g['name']),
646                                 'id'      => intval($g['id']),
647                                 'network' => $g['network'],
648                                 'link'    => $g['url'],
649                                 'nick'    => htmlentities(($g['attag']) ? $g['attag'] : $g['nick']),
650                                 'addr'    => htmlentities(($g['addr']) ? $g['addr'] : $g['url']),
651                                 'forum'   => ((x($g, 'forum') || x($g, 'prv')) ? 1 : 0),
652                         );
653                         if ($entry['forum']) {
654                                 $forums[] = $entry;
655                         } else {
656                                 $contacts[] = $entry;
657                         }
658                 }
659                 if (count($forums) > 0) {
660                         if ($search == "") {
661                                 $forums[] = array("separator" => true);
662                         }
663                         $contacts = array_merge($forums, $contacts);
664                 }
665         }
666
667         $items = array_merge($groups, $contacts);
668
669         if ($conv_id) {
670                 /*
671                  * if $conv_id is set, get unknown contacts in thread
672                  * but first get known contacts url to filter them out
673                  */
674                 $known_contacts = array_map(
675                         function ($i) {
676                                 return dbesc($i['link']);
677                         }
678                 , $contacts);
679
680                 $unknown_contacts = array();
681                 $r = q("SELECT `author-link`
682                                 FROM `item` WHERE `parent` = %d
683                                         AND (`author-name` LIKE '%%%s%%' OR `author-link` LIKE '%%%s%%')
684                                         AND `author-link` NOT IN ('%s')
685                                 GROUP BY `author-link`, `author-avatar`, `author-name`
686                                 ORDER BY `author-name` ASC
687                                 ",
688                                 intval($conv_id),
689                                 dbesc($search),
690                                 dbesc($search),
691                                 implode("', '", $known_contacts)
692                 );
693                 if (DBM::is_result($r)) {
694                         foreach ($r as $row) {
695                                 $contact = get_contact_details_by_url($row['author-link']);
696
697                                 if (count($contact) > 0) {
698                                         $unknown_contacts[] = array(
699                                                 'type'    => 'c',
700                                                 'photo'   => proxy_url($contact['micro'], false, PROXY_SIZE_MICRO),
701                                                 'name'    => htmlentities($contact['name']),
702                                                 'id'      => intval($contact['cid']),
703                                                 'network' => $contact['network'],
704                                                 'link'    => $contact['url'],
705                                                 'nick'    => htmlentities($contact['nick'] ? : $contact['addr']),
706                                                 'addr'    => htmlentities(($contact['addr']) ? $contact['addr'] : $contact['url']),
707                                                 'forum'   => $contact['forum']
708                                         );
709                                 }
710                         }
711                 }
712
713                 $items = array_merge($items, $unknown_contacts);
714                 $tot += count($unknown_contacts);
715         }
716
717         $results = array(
718                 'tot'      => $tot,
719                 'start'    => $start,
720                 'count'    => $count,
721                 'groups'   => $groups,
722                 'contacts' => $contacts,
723                 'items'    => $items,
724                 'type'     => $type,
725                 'search'   => $search,
726         );
727
728         call_hooks('acl_lookup_end', $results);
729
730         if ($out_type === 'html') {
731                 $o = array(
732                         'tot'      => $results['tot'],
733                         'start'    => $results['start'],
734                         'count'    => $results['count'],
735                         'groups'   => $results['groups'],
736                         'contacts' => $results['contacts'],
737                 );
738                 return $o;
739         }
740
741         $o = array(
742                 'tot'   => $results['tot'],
743                 'start' => $results['start'],
744                 'count' => $results['count'],
745                 'items' => $results['items'],
746         );
747
748         echo json_encode($o);
749
750         killme();
751 }
752 /**
753  * @brief Searching for global contacts for autocompletion
754  *
755  * @param App $a
756  * @return array with the search results
757  */
758 function navbar_complete(App $a) {
759
760 //      logger('navbar_complete');
761
762         if ((Config::get('system','block_public')) && (! local_user()) && (! remote_user())) {
763                 return;
764         }
765
766         // check if searching in the local global contact table is enabled
767         $localsearch = Config::get('system','poco_local_search');
768
769         $search = $prefix.notags(trim($_REQUEST['search']));
770         $mode = $_REQUEST['smode'];
771
772         // don't search if search term has less than 2 characters
773         if (! $search || mb_strlen($search) < 2) {
774                 return array();
775         }
776
777         if (substr($search,0,1) === '@') {
778                 $search = substr($search,1);
779         }
780
781         if ($localsearch) {
782                 $x = DirSearch::global_search_by_name($search, $mode);
783                 return $x;
784         }
785
786         if (! $localsearch) {
787                 $p = (($a->pager['page'] != 1) ? '&p=' . $a->pager['page'] : '');
788
789                 $x = z_fetch_url(get_server().'/lsearch?f=' . $p .  '&search=' . urlencode($search));
790                 if ($x['success']) {
791                         $t = 0;
792                         $j = json_decode($x['body'],true);
793                         if ($j && $j['results']) {
794                                 return $j['results'];
795                         }
796                 }
797         }
798
799         /// @TODO Not needed here?
800         return;
801 }