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