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