]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
Merge pull request #2860 from annando/1610-duplicate-check
[friendica.git] / include / Contact.php
1 <?php
2
3
4 // Included here for completeness, but this is a very dangerous operation.
5 // It is the caller's responsibility to confirm the requestor's intent and
6 // authorisation to do this.
7
8 function user_remove($uid) {
9         if(! $uid)
10                 return;
11         $a = get_app();
12         logger('Removing user: ' . $uid);
13
14         $r = q("select * from user where uid = %d limit 1", intval($uid));
15
16         call_hooks('remove_user',$r[0]);
17
18         // save username (actually the nickname as it is guaranteed
19         // unique), so it cannot be re-registered in the future.
20
21         q("insert into userd ( username ) values ( '%s' )",
22                 $r[0]['nickname']
23         );
24
25         // don't delete yet, will be done later when contacts have deleted my stuff
26         // q("DELETE FROM `contact` WHERE `uid` = %d", intval($uid));
27         q("DELETE FROM `gcign` WHERE `uid` = %d", intval($uid));
28         q("DELETE FROM `group` WHERE `uid` = %d", intval($uid));
29         q("DELETE FROM `group_member` WHERE `uid` = %d", intval($uid));
30         q("DELETE FROM `intro` WHERE `uid` = %d", intval($uid));
31         q("DELETE FROM `event` WHERE `uid` = %d", intval($uid));
32         q("DELETE FROM `item` WHERE `uid` = %d", intval($uid));
33         q("DELETE FROM `item_id` WHERE `uid` = %d", intval($uid));
34         q("DELETE FROM `mail` WHERE `uid` = %d", intval($uid));
35         q("DELETE FROM `mailacct` WHERE `uid` = %d", intval($uid));
36         q("DELETE FROM `manage` WHERE `uid` = %d", intval($uid));
37         q("DELETE FROM `notify` WHERE `uid` = %d", intval($uid));
38         q("DELETE FROM `photo` WHERE `uid` = %d", intval($uid));
39         q("DELETE FROM `attach` WHERE `uid` = %d", intval($uid));
40         q("DELETE FROM `profile` WHERE `uid` = %d", intval($uid));
41         q("DELETE FROM `profile_check` WHERE `uid` = %d", intval($uid));
42         q("DELETE FROM `pconfig` WHERE `uid` = %d", intval($uid));
43         q("DELETE FROM `search` WHERE `uid` = %d", intval($uid));
44         q("DELETE FROM `spam` WHERE `uid` = %d", intval($uid));
45         // don't delete yet, will be done later when contacts have deleted my stuff
46         // q("DELETE FROM `user` WHERE `uid` = %d", intval($uid));
47         q("UPDATE `user` SET `account_removed` = 1, `account_expires_on` = UTC_TIMESTAMP() WHERE `uid` = %d", intval($uid));
48         proc_run(PRIORITY_HIGH, "include/notifier.php", "removeme", $uid);
49
50         // Send an update to the directory
51         proc_run(PRIORITY_LOW, "include/directory.php", $r[0]['url']);
52
53         if($uid == local_user()) {
54                 unset($_SESSION['authenticated']);
55                 unset($_SESSION['uid']);
56                 goaway($a->get_baseurl());
57         }
58 }
59
60
61 function contact_remove($id) {
62
63         $r = q("select uid from contact where id = %d limit 1",
64                 intval($id)
65         );
66         if((! count($r)) || (! intval($r[0]['uid'])))
67                 return;
68
69         $archive = get_pconfig($r[0]['uid'], 'system','archive_removed_contacts');
70         if($archive) {
71                 q("update contact set `archive` = 1, `network` = 'none', `writable` = 0 where id = %d",
72                         intval($id)
73                 );
74                 return;
75         }
76
77         q("DELETE FROM `contact` WHERE `id` = %d",
78                 intval($id)
79         );
80         q("DELETE FROM `item` WHERE `contact-id` = %d ",
81                 intval($id)
82         );
83         q("DELETE FROM `photo` WHERE `contact-id` = %d ",
84                 intval($id)
85         );
86         q("DELETE FROM `mail` WHERE `contact-id` = %d ",
87                 intval($id)
88         );
89         q("DELETE FROM `event` WHERE `cid` = %d ",
90                 intval($id)
91         );
92         q("DELETE FROM `queue` WHERE `cid` = %d ",
93                 intval($id)
94         );
95
96 }
97
98
99 // sends an unfriend message. Does not remove the contact
100
101 function terminate_friendship($user,$self,$contact) {
102
103
104         $a = get_app();
105
106         require_once('include/datetime.php');
107
108         if($contact['network'] === NETWORK_OSTATUS) {
109
110                 $slap = replace_macros(get_markup_template('follow_slap.tpl'), array(
111                         '$name' => $user['username'],
112                         '$profile_page' => $a->get_baseurl() . '/profile/' . $user['nickname'],
113                         '$photo' => $self['photo'],
114                         '$thumb' => $self['thumb'],
115                         '$published' => datetime_convert('UTC','UTC', 'now', ATOM_TIME),
116                         '$item_id' => 'urn:X-dfrn:' . $a->get_hostname() . ':unfollow:' . get_guid(32),
117                         '$title' => '',
118                         '$type' => 'text',
119                         '$content' => t('stopped following'),
120                         '$nick' => $user['nickname'],
121                         '$verb' => 'http://ostatus.org/schema/1.0/unfollow', // ACTIVITY_UNFOLLOW,
122                         '$ostat_follow' => '' // '<as:verb>http://ostatus.org/schema/1.0/unfollow</as:verb>' . "\r\n"
123                 ));
124
125                 if((x($contact,'notify')) && (strlen($contact['notify']))) {
126                         require_once('include/salmon.php');
127                         slapper($user,$contact['notify'],$slap);
128                 }
129         }
130         elseif($contact['network'] === NETWORK_DIASPORA) {
131                 require_once('include/diaspora.php');
132                 diaspora::send_unshare($user,$contact);
133         }
134         elseif($contact['network'] === NETWORK_DFRN) {
135                 require_once('include/dfrn.php');
136                 dfrn::deliver($user,$contact,'placeholder', 1);
137         }
138
139 }
140
141
142 // Contact has refused to recognise us as a friend. We will start a countdown.
143 // If they still don't recognise us in 32 days, the relationship is over,
144 // and we won't waste any more time trying to communicate with them.
145 // This provides for the possibility that their database is temporarily messed
146 // up or some other transient event and that there's a possibility we could recover from it.
147
148 if(! function_exists('mark_for_death')) {
149 function mark_for_death($contact) {
150
151         if($contact['archive'])
152                 return;
153
154         if($contact['term-date'] == '0000-00-00 00:00:00') {
155                 q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
156                                 dbesc(datetime_convert()),
157                                 intval($contact['id'])
158                 );
159         }
160         else {
161
162                 /// @todo
163                 /// We really should send a notification to the owner after 2-3 weeks
164                 /// so they won't be surprised when the contact vanishes and can take
165                 /// remedial action if this was a serious mistake or glitch
166
167                 $expiry = $contact['term-date'] . ' + 32 days ';
168                 if(datetime_convert() > datetime_convert('UTC','UTC',$expiry)) {
169
170                         // relationship is really truly dead.
171                         // archive them rather than delete
172                         // though if the owner tries to unarchive them we'll start the whole process over again
173
174                         q("update contact set `archive` = 1 where id = %d",
175                                 intval($contact['id'])
176                         );
177                         q("UPDATE `item` SET `private` = 2 WHERE `contact-id` = %d AND `uid` = %d", intval($contact['id']), intval($contact['uid']));
178
179                         //contact_remove($contact['id']);
180
181                 }
182         }
183
184 }}
185
186 if(! function_exists('unmark_for_death')) {
187 function unmark_for_death($contact) {
188         // It's a miracle. Our dead contact has inexplicably come back to life.
189         q("UPDATE `contact` SET `term-date` = '%s' WHERE `id` = %d",
190                 dbesc('0000-00-00 00:00:00'),
191                 intval($contact['id'])
192         );
193 }}
194
195 /**
196  * @brief Get contact data for a given profile link
197  *
198  * The function looks at several places (contact table and gcontact table) for the contact
199  *
200  * @param string $url The profile link
201  * @param int $uid User id
202  * @param array $default If not data was found take this data as default value
203  *
204  * @return array Contact data
205  */
206 function get_contact_details_by_url($url, $uid = -1, $default = array()) {
207         if ($uid == -1)
208                 $uid = local_user();
209
210         // Fetch contact data from the contact table for the given user
211         $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
212                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
213                 FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
214                         dbesc(normalise_link($url)), intval($uid));
215
216         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
217         if (!$r)
218                 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
219                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
220                         FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
221                                 dbesc(normalise_link($url)));
222
223         // Fetch the data from the gcontact table
224         if (!$r)
225                 $r = q("SELECT 0 AS `id`, 0 AS `cid`, `id` AS `gid`, 0 AS `zid`, 0 AS `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, '' AS `xmpp`,
226                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
227                         FROM `gcontact` WHERE `nurl` = '%s'",
228                                 dbesc(normalise_link($url)));
229
230         if ($r) {
231                 // If there is more than one entry we filter out the connector networks
232                 if (count($r) > 1)
233                         foreach ($r AS $id => $result)
234                                 if ($result["network"] == NETWORK_STATUSNET)
235                                         unset($r[$id]);
236
237                 $profile = array_shift($r);
238
239                 // "bd" always contains the upcoming birthday of a contact.
240                 // "birthday" might contain the birthday including the year of birth.
241                 if ($profile["birthday"] != "0000-00-00") {
242                         $bd_timestamp = strtotime($profile["birthday"]);
243                         $month = date("m", $bd_timestamp);
244                         $day = date("d", $bd_timestamp);
245
246                         $current_timestamp = time();
247                         $current_year = date("Y", $current_timestamp);
248                         $current_month = date("m", $current_timestamp);
249                         $current_day = date("d", $current_timestamp);
250
251                         $profile["bd"] = $current_year."-".$month."-".$day;
252                         $current = $current_year."-".$current_month."-".$current_day;
253
254                         if ($profile["bd"] < $current)
255                                 $profile["bd"] = (++$current_year)."-".$month."-".$day;
256                 } else
257                         $profile["bd"] = "0000-00-00";
258         } else
259                 $profile = $default;
260
261         if (($profile["photo"] == "") AND isset($default["photo"]))
262                 $profile["photo"] = $default["photo"];
263
264         if (($profile["name"] == "") AND isset($default["name"]))
265                 $profile["name"] = $default["name"];
266
267         if (($profile["network"] == "") AND isset($default["network"]))
268                 $profile["network"] = $default["network"];
269
270         if (($profile["thumb"] == "") AND isset($profile["photo"]))
271                 $profile["thumb"] = $profile["photo"];
272
273         if (($profile["micro"] == "") AND isset($profile["thumb"]))
274                 $profile["micro"] = $profile["thumb"];
275
276         if ((($profile["addr"] == "") OR ($profile["name"] == "")) AND ($profile["gid"] != 0) AND
277                 in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS)))
278                 proc_run(PRIORITY_LOW, "include/update_gcontact.php", $profile["gid"]);
279
280         // Show contact details of Diaspora contacts only if connected
281         if (($profile["cid"] == 0) AND ($profile["network"] == NETWORK_DIASPORA)) {
282                 $profile["location"] = "";
283                 $profile["about"] = "";
284                 $profile["gender"] = "";
285                 $profile["birthday"] = "0000-00-00";
286         }
287
288         return($profile);
289 }
290
291 if (! function_exists('contact_photo_menu')) {
292 function contact_photo_menu($contact, $uid = 0)
293 {
294         $a = get_app();
295
296         $contact_url = '';
297         $pm_url = '';
298         $status_link = '';
299         $photos_link = '';
300         $posts_link = '';
301         $contact_drop_link = '';
302         $poke_link = '';
303
304         if ($uid == 0) {
305                 $uid = local_user();
306         }
307
308         if ($contact['uid'] != $uid) {
309                 if ($uid == 0) {
310                         $profile_link = zrl($contact['url']);
311                         $menu = Array('profile' => array(t('View Profile'), $profile_link, true));
312
313                         return $menu;
314                 }
315
316                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `network` = '%s' AND `uid` = %d",
317                         dbesc($contact['nurl']), dbesc($contact['network']), intval($uid));
318                 if ($r) {
319                         return contact_photo_menu($r[0], $uid);
320                 } else {
321                         $profile_link = zrl($contact['url']);
322                         $connlnk = 'follow/?url='.$contact['url'];
323                         $menu = array(
324                                 'profile' => array(t('View Profile'), $profile_link, true),
325                                 'follow' => array(t('Connect/Follow'), $connlnk, true)
326                         );
327
328                         return $menu;
329                 }
330         }
331
332         $sparkle = false;
333         if ($contact['network'] === NETWORK_DFRN) {
334                 $sparkle = true;
335                 $profile_link = $a->get_baseurl() . '/redir/' . $contact['id'];
336         } else {
337                 $profile_link = $contact['url'];
338         }
339
340         if ($profile_link === 'mailbox') {
341                 $profile_link = '';
342         }
343
344         if ($sparkle) {
345                 $status_link = $profile_link . '?url=status';
346                 $photos_link = $profile_link . '?url=photos';
347                 $profile_link = $profile_link . '?url=profile';
348         }
349
350         if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
351                 $pm_url = $a->get_baseurl() . '/message/new/' . $contact['id'];
352         }
353
354         if ($contact['network'] == NETWORK_DFRN) {
355                 $poke_link = $a->get_baseurl() . '/poke/?f=&c=' . $contact['id'];
356         }
357
358         $contact_url = $a->get_baseurl() . '/contacts/' . $contact['id'];
359
360         $posts_link = $a->get_baseurl() . '/contacts/' . $contact['id'] . '/posts';
361         $contact_drop_link = $a->get_baseurl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
362
363         /**
364          * menu array:
365          * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
366          */
367         $menu = array(
368                 'status' => array(t("View Status"), $status_link, true),
369                 'profile' => array(t("View Profile"), $profile_link, true),
370                 'photos' => array(t("View Photos"), $photos_link, true),
371                 'network' => array(t("Network Posts"), $posts_link, false),
372                 'edit' => array(t("View Contact"), $contact_url, false),
373                 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
374                 'pm' => array(t("Send PM"), $pm_url, false),
375                 'poke' => array(t("Poke"), $poke_link, false),
376         );
377
378
379         $args = array('contact' => $contact, 'menu' => &$menu);
380
381         call_hooks('contact_photo_menu', $args);
382
383         $menucondensed = array();
384
385         foreach ($menu AS $menuname => $menuitem) {
386                 if ($menuitem[1] != '') {
387                         $menucondensed[$menuname] = $menuitem;
388                 }
389         }
390
391         return $menucondensed;
392 }}
393
394
395 function random_profile() {
396         $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
397                                 AND `last_contact` >= `last_failure`
398                                 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
399                         ORDER BY rand() LIMIT 1",
400                 dbesc(NETWORK_DFRN));
401
402         if(count($r))
403                 return dirname($r[0]['url']);
404         return '';
405 }
406
407
408 function contacts_not_grouped($uid,$start = 0,$count = 0) {
409
410         if(! $count) {
411                 $r = q("select count(*) as total from contact where uid = %d and self = 0 and id not in (select distinct(`contact-id`) from group_member where uid = %d) ",
412                         intval($uid),
413                         intval($uid)
414                 );
415
416                 return $r;
417
418
419         }
420
421         $r = q("select * from contact where uid = %d and self = 0 and id not in (select distinct(`contact-id`) from group_member where uid = %d) and blocked = 0 and pending = 0 limit %d, %d",
422                 intval($uid),
423                 intval($uid),
424                 intval($start),
425                 intval($count)
426         );
427
428         return $r;
429 }
430
431 function get_contact($url, $uid = 0) {
432         require_once("include/Scrape.php");
433
434         $data = array();
435         $contactid = 0;
436
437         // is it an address in the format user@server.tld?
438         /// @todo use gcontact and/or the addr field for a lookup
439         if (!strstr($url, "http") OR strstr($url, "@")) {
440                 $data = probe_url($url);
441                 $url = $data["url"];
442                 if ($url == "")
443                         return 0;
444         }
445
446         $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
447                         dbesc(normalise_link($url)),
448                         intval($uid));
449
450         if (!$contact)
451                 $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `uid` = %d ORDER BY `id` LIMIT 1",
452                                 dbesc($url),
453                                 dbesc(normalise_link($url)),
454                                 intval($uid));
455
456         if ($contact) {
457                 $contactid = $contact[0]["id"];
458
459                 // Update the contact every 7 days
460                 $update_photo = ($contact[0]['avatar-date'] < datetime_convert('','','now -7 days'));
461                 //$update_photo = ($contact[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
462
463                 if (!$update_photo)
464                         return($contactid);
465         } elseif ($uid != 0)
466                 return 0;
467
468         if (!count($data))
469                 $data = probe_url($url);
470
471         // Does this address belongs to a valid network?
472         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
473                 if ($uid != 0)
474                         return 0;
475
476                 // Get data from the gcontact table
477                 $r = q("SELECT `name`, `nick`, `url`, `photo`, `addr`, `alias`, `network` FROM `gcontact` WHERE `nurl` = '%s'",
478                          dbesc(normalise_link($url)));
479                 if (!$r)
480                         return 0;
481
482                 $data = $r[0];
483         }
484
485         $url = $data["url"];
486
487         if ($contactid == 0) {
488                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
489                                         `name`, `nick`, `photo`, `network`, `pubkey`, `rel`, `priority`,
490                                         `batch`, `request`, `confirm`, `poco`,
491                                         `writable`, `blocked`, `readonly`, `pending`)
492                                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', '%s', '%s', 1, 0, 0, 0)",
493                         intval($uid),
494                         dbesc(datetime_convert()),
495                         dbesc($data["url"]),
496                         dbesc(normalise_link($data["url"])),
497                         dbesc($data["addr"]),
498                         dbesc($data["alias"]),
499                         dbesc($data["notify"]),
500                         dbesc($data["poll"]),
501                         dbesc($data["name"]),
502                         dbesc($data["nick"]),
503                         dbesc($data["photo"]),
504                         dbesc($data["network"]),
505                         dbesc($data["pubkey"]),
506                         intval(CONTACT_IS_SHARING),
507                         intval($data["priority"]),
508                         dbesc($data["batch"]),
509                         dbesc($data["request"]),
510                         dbesc($data["confirm"]),
511                         dbesc($data["poco"])
512                 );
513
514                 $contact = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
515                                 dbesc(normalise_link($data["url"])),
516                                 intval($uid));
517                 if (!$contact)
518                         return 0;
519
520                 $contactid = $contact[0]["id"];
521
522                 // Update the newly created contact from data in the gcontact table
523                 $r = q("SELECT `location`, `about`, `keywords`, `gender` FROM `gcontact` WHERE `nurl` = '%s'",
524                          dbesc(normalise_link($data["url"])));
525                 if ($r) {
526                         logger("Update contact ".$data["url"]);
527                         q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d",
528                                 dbesc($r["location"]), dbesc($r["about"]), dbesc($r["keywords"]),
529                                 dbesc($r["gender"]), intval($contactid));
530                 }
531         }
532
533         if ((count($contact) > 1) AND ($uid == 0) AND ($contactid != 0) AND ($url != ""))
534                 q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d",
535                         dbesc(normalise_link($url)),
536                         intval($contactid));
537
538         require_once("Photo.php");
539
540         update_contact_avatar($data["photo"],$uid,$contactid);
541
542         q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
543                 `name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
544                 dbesc($data["addr"]),
545                 dbesc($data["alias"]),
546                 dbesc($data["name"]),
547                 dbesc($data["nick"]),
548                 dbesc(datetime_convert()),
549                 dbesc(datetime_convert()),
550                 intval($contactid)
551         );
552
553         return $contactid;
554 }
555
556 /**
557  * @brief Returns posts from a given gcontact
558  *
559  * @param App $a argv application class
560  * @param int $gcontact_id Global contact
561  *
562  * @return string posts in HTML
563  */
564 function posts_from_gcontact($a, $gcontact_id) {
565
566         require_once('include/conversation.php');
567
568         // There are no posts with "uid = 0" with connector networks
569         // This speeds up the query a lot
570         $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
571         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
572                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
573         else
574                 $sql = "`item`.`uid` = %d";
575
576         if(get_config('system', 'old_pager')) {
577                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
578                         WHERE `gcontact-id` = %d and $sql",
579                         intval($gcontact_id),
580                         intval(local_user()));
581
582                 $a->set_pager_total($r[0]['total']);
583         }
584
585         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
586                         `author-name` AS `name`, `owner-avatar` AS `photo`,
587                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
588                 FROM `item` FORCE INDEX (`gcontactid_uid_created`)
589                 WHERE `gcontact-id` = %d AND $sql AND
590                         NOT `deleted` AND NOT `moderated` AND `visible`
591                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
592                 intval($gcontact_id),
593                 intval(local_user()),
594                 intval($a->pager['start']),
595                 intval($a->pager['itemspage'])
596         );
597
598         $o = conversation($a,$r,'community',false);
599
600         if(!get_config('system', 'old_pager')) {
601                 $o .= alt_pager($a,count($r));
602         } else {
603                 $o .= paginate($a);
604         }
605
606         return $o;
607 }
608
609 /**
610  * @brief Returns posts from a given contact
611  *
612  * @param App $a argv application class
613  * @param int $contact_id contact
614  *
615  * @return string posts in HTML
616  */
617 function posts_from_contact($a, $contact_id) {
618
619         require_once('include/conversation.php');
620
621         $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id));
622         if (!$r)
623                 return false;
624
625         $contact = $r[0];
626
627         if(get_config('system', 'old_pager')) {
628                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
629                         WHERE `item`.`uid` = %d AND `author-link` IN ('%s', '%s')",
630                         intval(local_user()),
631                         dbesc(str_replace("https://", "http://", $contact["url"])),
632                         dbesc(str_replace("http://", "https://", $contact["url"])));
633
634                 $a->set_pager_total($r[0]['total']);
635         }
636
637         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
638                         `author-name` AS `name`, `owner-avatar` AS `photo`,
639                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
640                 FROM `item` FORCE INDEX (`uid_contactid_id`)
641                 WHERE `item`.`uid` = %d AND `contact-id` = %d
642                         AND `author-link` IN ('%s', '%s')
643                         AND NOT `deleted` AND NOT `moderated` AND `visible`
644                 ORDER BY `item`.`id` DESC LIMIT %d, %d",
645                 intval(local_user()),
646                 intval($contact_id),
647                 dbesc(str_replace("https://", "http://", $contact["url"])),
648                 dbesc(str_replace("http://", "https://", $contact["url"])),
649                 intval($a->pager['start']),
650                 intval($a->pager['itemspage'])
651         );
652
653         $o .= conversation($a,$r,'community',false);
654
655         if(!get_config('system', 'old_pager'))
656                 $o .= alt_pager($a,count($r));
657         else
658                 $o .= paginate($a);
659
660         return $o;
661 }
662
663 /**
664  * @brief Returns a formatted location string from the given profile array
665  *
666  * @param array $profile Profile array (Generated from the "profile" table)
667  *
668  * @return string Location string
669  */
670 function formatted_location($profile) {
671         $location = '';
672
673         if($profile['locality'])
674                 $location .= $profile['locality'];
675
676         if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
677                 if($location)
678                         $location .= ', ';
679
680                 $location .= $profile['region'];
681         }
682
683         if($profile['country-name']) {
684                 if($location)
685                         $location .= ', ';
686
687                 $location .= $profile['country-name'];
688         }
689
690         return $location;
691 }
692
693 /**
694  * @brief Returns the account type name
695  *
696  * The function can be called with either the user or the contact array
697  *
698  * @param array $contact contact or user array
699  */
700 function account_type($contact) {
701
702         // There are several fields that indicate that the contact or user is a forum
703         // "page-flags" is a field in the user table,
704         // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
705         // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
706         if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
707                 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
708                 || (isset($contact['forum']) && intval($contact['forum']))
709                 || (isset($contact['prv']) && intval($contact['prv']))
710                 || (isset($contact['community']) && intval($contact['community'])))
711                 $type = ACCOUNT_TYPE_COMMUNITY;
712         else
713                 $type = ACCOUNT_TYPE_PERSON;
714
715         // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
716         if (isset($contact["contact-type"]))
717                 $type = $contact["contact-type"];
718         if (isset($contact["account-type"]))
719                 $type = $contact["account-type"];
720
721         switch($type) {
722                 case ACCOUNT_TYPE_ORGANISATION:
723                         $account_type = t("Organisation");
724                         break;
725                 case ACCOUNT_TYPE_NEWS:
726                         $account_type = t('News');
727                         break;
728                 case ACCOUNT_TYPE_COMMUNITY:
729                         $account_type = t("Forum");
730                         break;
731                 default:
732                         $account_type = "";
733                         break;
734         }
735
736         return $account_type;
737 }
738 ?>