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