]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
Merge pull request #2898 from tobiasd/20161109-debbcide
[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  * It caches its result for the same script execution to prevent duplicate calls
200  *
201  * @param string $url The profile link
202  * @param int $uid User id
203  * @param array $default If not data was found take this data as default value
204  *
205  * @return array Contact data
206  */
207 function get_contact_details_by_url($url, $uid = -1, $default = array()) {
208         static $cache = array();
209
210         if ($uid == -1) {
211                 $uid = local_user();
212         }
213
214         if (isset($cache[$url][$uid])) {
215                 return $cache[$url][$uid];
216         }
217
218         // Fetch contact data from the contact table for the given user
219         $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
220                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
221                 FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d",
222                         dbesc(normalise_link($url)), intval($uid));
223
224         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
225         if (!$r)
226                 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `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`, 0 AS `self`
228                         FROM `contact` WHERE `nurl` = '%s' AND `uid` = 0",
229                                 dbesc(normalise_link($url)));
230
231         // Fetch the data from the gcontact table
232         if (!$r)
233                 $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`,
234                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
235                         FROM `gcontact` WHERE `nurl` = '%s'",
236                                 dbesc(normalise_link($url)));
237
238         if ($r) {
239                 // If there is more than one entry we filter out the connector networks
240                 if (count($r) > 1) {
241                         foreach ($r AS $id => $result) {
242                                 if ($result["network"] == NETWORK_STATUSNET) {
243                                         unset($r[$id]);
244                                 }
245                         }
246                 }
247
248                 $profile = array_shift($r);
249
250                 // "bd" always contains the upcoming birthday of a contact.
251                 // "birthday" might contain the birthday including the year of birth.
252                 if ($profile["birthday"] != "0000-00-00") {
253                         $bd_timestamp = strtotime($profile["birthday"]);
254                         $month = date("m", $bd_timestamp);
255                         $day = date("d", $bd_timestamp);
256
257                         $current_timestamp = time();
258                         $current_year = date("Y", $current_timestamp);
259                         $current_month = date("m", $current_timestamp);
260                         $current_day = date("d", $current_timestamp);
261
262                         $profile["bd"] = $current_year."-".$month."-".$day;
263                         $current = $current_year."-".$current_month."-".$current_day;
264
265                         if ($profile["bd"] < $current) {
266                                 $profile["bd"] = (++$current_year)."-".$month."-".$day;
267                         }
268                 } else {
269                         $profile["bd"] = "0000-00-00";
270                 }
271         } else {
272                 $profile = $default;
273         }
274
275         if (($profile["photo"] == "") AND isset($default["photo"])) {
276                 $profile["photo"] = $default["photo"];
277         }
278
279         if (($profile["name"] == "") AND isset($default["name"])) {
280                 $profile["name"] = $default["name"];
281         }
282
283         if (($profile["network"] == "") AND isset($default["network"])) {
284                 $profile["network"] = $default["network"];
285         }
286
287         if (($profile["thumb"] == "") AND isset($profile["photo"])) {
288                 $profile["thumb"] = $profile["photo"];
289         }
290
291         if (($profile["micro"] == "") AND isset($profile["thumb"])) {
292                 $profile["micro"] = $profile["thumb"];
293         }
294
295         if ((($profile["addr"] == "") OR ($profile["name"] == "")) AND ($profile["gid"] != 0) AND
296                 in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
297                 proc_run(PRIORITY_LOW, "include/update_gcontact.php", $profile["gid"]);
298         }
299
300         // Show contact details of Diaspora contacts only if connected
301         if (($profile["cid"] == 0) AND ($profile["network"] == NETWORK_DIASPORA)) {
302                 $profile["location"] = "";
303                 $profile["about"] = "";
304                 $profile["gender"] = "";
305                 $profile["birthday"] = "0000-00-00";
306         }
307
308         $cache[$url][$uid] = $profile;
309
310         return $profile;
311 }
312
313 if (! function_exists('contact_photo_menu')) {
314 function contact_photo_menu($contact, $uid = 0)
315 {
316         $a = get_app();
317
318         $contact_url = '';
319         $pm_url = '';
320         $status_link = '';
321         $photos_link = '';
322         $posts_link = '';
323         $contact_drop_link = '';
324         $poke_link = '';
325
326         if ($uid == 0) {
327                 $uid = local_user();
328         }
329
330         if ($contact['uid'] != $uid) {
331                 if ($uid == 0) {
332                         $profile_link = zrl($contact['url']);
333                         $menu = Array('profile' => array(t('View Profile'), $profile_link, true));
334
335                         return $menu;
336                 }
337
338                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `network` = '%s' AND `uid` = %d",
339                         dbesc($contact['nurl']), dbesc($contact['network']), intval($uid));
340                 if ($r) {
341                         return contact_photo_menu($r[0], $uid);
342                 } else {
343                         $profile_link = zrl($contact['url']);
344                         $connlnk = 'follow/?url='.$contact['url'];
345                         $menu = array(
346                                 'profile' => array(t('View Profile'), $profile_link, true),
347                                 'follow' => array(t('Connect/Follow'), $connlnk, true)
348                         );
349
350                         return $menu;
351                 }
352         }
353
354         $sparkle = false;
355         if ($contact['network'] === NETWORK_DFRN) {
356                 $sparkle = true;
357                 $profile_link = $a->get_baseurl() . '/redir/' . $contact['id'];
358         } else {
359                 $profile_link = $contact['url'];
360         }
361
362         if ($profile_link === 'mailbox') {
363                 $profile_link = '';
364         }
365
366         if ($sparkle) {
367                 $status_link = $profile_link . '?url=status';
368                 $photos_link = $profile_link . '?url=photos';
369                 $profile_link = $profile_link . '?url=profile';
370         }
371
372         if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
373                 $pm_url = $a->get_baseurl() . '/message/new/' . $contact['id'];
374         }
375
376         if ($contact['network'] == NETWORK_DFRN) {
377                 $poke_link = $a->get_baseurl() . '/poke/?f=&c=' . $contact['id'];
378         }
379
380         $contact_url = $a->get_baseurl() . '/contacts/' . $contact['id'];
381
382         $posts_link = $a->get_baseurl() . '/contacts/' . $contact['id'] . '/posts';
383         $contact_drop_link = $a->get_baseurl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
384
385         /**
386          * menu array:
387          * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
388          */
389         $menu = array(
390                 'status' => array(t("View Status"), $status_link, true),
391                 'profile' => array(t("View Profile"), $profile_link, true),
392                 'photos' => array(t("View Photos"), $photos_link, true),
393                 'network' => array(t("Network Posts"), $posts_link, false),
394                 'edit' => array(t("View Contact"), $contact_url, false),
395                 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
396                 'pm' => array(t("Send PM"), $pm_url, false),
397                 'poke' => array(t("Poke"), $poke_link, false),
398         );
399
400
401         $args = array('contact' => $contact, 'menu' => &$menu);
402
403         call_hooks('contact_photo_menu', $args);
404
405         $menucondensed = array();
406
407         foreach ($menu AS $menuname => $menuitem) {
408                 if ($menuitem[1] != '') {
409                         $menucondensed[$menuname] = $menuitem;
410                 }
411         }
412
413         return $menucondensed;
414 }}
415
416
417 function random_profile() {
418         $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
419                                 AND `last_contact` >= `last_failure`
420                                 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
421                         ORDER BY rand() LIMIT 1",
422                 dbesc(NETWORK_DFRN));
423
424         if(count($r))
425                 return dirname($r[0]['url']);
426         return '';
427 }
428
429
430 function contacts_not_grouped($uid,$start = 0,$count = 0) {
431
432         if(! $count) {
433                 $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) ",
434                         intval($uid),
435                         intval($uid)
436                 );
437
438                 return $r;
439
440
441         }
442
443         $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",
444                 intval($uid),
445                 intval($uid),
446                 intval($start),
447                 intval($count)
448         );
449
450         return $r;
451 }
452
453 /**
454  * @brief Fetch the contact id for a given url and user
455  *
456  * @param string $url Contact URL
457  * @param integer $uid The user id for the contact
458  * @param boolean $no_update Don't update the contact
459  *
460  * @return integer Contact ID
461  */
462 function get_contact($url, $uid = 0, $no_update = false) {
463         require_once("include/Scrape.php");
464
465         logger("Get contact data for url ".$url." and user ".$uid." - ".App::callstack(), LOGGER_DEBUG);;
466
467         $data = array();
468         $contactid = 0;
469
470         // is it an address in the format user@server.tld?
471         /// @todo use gcontact and/or the addr field for a lookup
472         if (!strstr($url, "http") OR strstr($url, "@")) {
473                 $data = probe_url($url);
474                 $url = $data["url"];
475                 if ($url == "")
476                         return 0;
477         }
478
479         $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
480                         dbesc(normalise_link($url)),
481                         intval($uid));
482
483         if (!$contact)
484                 $contact = q("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN ('%s', '%s') AND `uid` = %d ORDER BY `id` LIMIT 1",
485                                 dbesc($url),
486                                 dbesc(normalise_link($url)),
487                                 intval($uid));
488
489         if ($contact) {
490                 $contactid = $contact[0]["id"];
491
492                 // Update the contact every 7 days
493                 $update_photo = ($contact[0]['avatar-date'] < datetime_convert('','','now -7 days'));
494                 //$update_photo = ($contact[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
495
496                 if (!$update_photo OR $no_update) {
497                         return($contactid);
498                 }
499         } elseif ($uid != 0)
500                 return 0;
501
502         if (!count($data))
503                 $data = probe_url($url);
504
505         // Does this address belongs to a valid network?
506         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
507                 if ($uid != 0)
508                         return 0;
509
510                 // Get data from the gcontact table
511                 $r = q("SELECT `name`, `nick`, `url`, `photo`, `addr`, `alias`, `network` FROM `gcontact` WHERE `nurl` = '%s'",
512                          dbesc(normalise_link($url)));
513                 if (!$r)
514                         return 0;
515
516                 $data = $r[0];
517         }
518
519         $url = $data["url"];
520
521         if ($contactid == 0) {
522                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
523                                         `name`, `nick`, `photo`, `network`, `pubkey`, `rel`, `priority`,
524                                         `batch`, `request`, `confirm`, `poco`, `name-date`, `uri-date`,
525                                         `writable`, `blocked`, `readonly`, `pending`)
526                                         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)",
527                         intval($uid),
528                         dbesc(datetime_convert()),
529                         dbesc($data["url"]),
530                         dbesc(normalise_link($data["url"])),
531                         dbesc($data["addr"]),
532                         dbesc($data["alias"]),
533                         dbesc($data["notify"]),
534                         dbesc($data["poll"]),
535                         dbesc($data["name"]),
536                         dbesc($data["nick"]),
537                         dbesc($data["photo"]),
538                         dbesc($data["network"]),
539                         dbesc($data["pubkey"]),
540                         intval(CONTACT_IS_SHARING),
541                         intval($data["priority"]),
542                         dbesc($data["batch"]),
543                         dbesc($data["request"]),
544                         dbesc($data["confirm"]),
545                         dbesc($data["poco"]),
546                         dbesc(datetime_convert()),
547                         dbesc(datetime_convert())
548                 );
549
550                 $contact = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
551                                 dbesc(normalise_link($data["url"])),
552                                 intval($uid));
553                 if (!$contact)
554                         return 0;
555
556                 $contactid = $contact[0]["id"];
557
558                 // Update the newly created contact from data in the gcontact table
559                 $r = q("SELECT `location`, `about`, `keywords`, `gender` FROM `gcontact` WHERE `nurl` = '%s'",
560                          dbesc(normalise_link($data["url"])));
561                 if ($r) {
562                         logger("Update contact ".$data["url"]);
563                         q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d",
564                                 dbesc($r["location"]), dbesc($r["about"]), dbesc($r["keywords"]),
565                                 dbesc($r["gender"]), intval($contactid));
566                 }
567         }
568
569         if ((count($contact) > 1) AND ($uid == 0) AND ($contactid != 0) AND ($url != ""))
570                 q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d",
571                         dbesc(normalise_link($url)),
572                         intval($contactid));
573
574         require_once("Photo.php");
575
576         update_contact_avatar($data["photo"],$uid,$contactid);
577
578         $r = q("SELECT `addr`, `alias`, `name`, `nick` FROM `contact`  WHERE `id` = %d", intval($contactid));
579
580         // This condition should always be true
581         if (!dbm::is_result($r))
582                 return $contactid;
583
584         // Only update if there had something been changed
585         if (($data["addr"] != $r[0]["addr"]) OR
586                 ($data["alias"] != $r[0]["alias"]) OR
587                 ($data["name"] != $r[0]["name"]) OR
588                 ($data["nick"] != $r[0]["nick"]))
589                 q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
590                         `name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
591                         dbesc($data["addr"]),
592                         dbesc($data["alias"]),
593                         dbesc($data["name"]),
594                         dbesc($data["nick"]),
595                         dbesc(datetime_convert()),
596                         dbesc(datetime_convert()),
597                         intval($contactid)
598                 );
599
600         return $contactid;
601 }
602
603 /**
604  * @brief Returns posts from a given gcontact
605  *
606  * @param App $a argv application class
607  * @param int $gcontact_id Global contact
608  *
609  * @return string posts in HTML
610  */
611 function posts_from_gcontact($a, $gcontact_id) {
612
613         require_once('include/conversation.php');
614
615         // There are no posts with "uid = 0" with connector networks
616         // This speeds up the query a lot
617         $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
618         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
619                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
620         else
621                 $sql = "`item`.`uid` = %d";
622
623         if(get_config('system', 'old_pager')) {
624                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
625                         WHERE `gcontact-id` = %d and $sql",
626                         intval($gcontact_id),
627                         intval(local_user()));
628
629                 $a->set_pager_total($r[0]['total']);
630         }
631
632         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
633                         `author-name` AS `name`, `owner-avatar` AS `photo`,
634                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
635                 FROM `item` FORCE INDEX (`gcontactid_uid_created`)
636                 WHERE `gcontact-id` = %d AND $sql AND
637                         NOT `deleted` AND NOT `moderated` AND `visible`
638                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
639                 intval($gcontact_id),
640                 intval(local_user()),
641                 intval($a->pager['start']),
642                 intval($a->pager['itemspage'])
643         );
644
645         $o = conversation($a,$r,'community',false);
646
647         if(!get_config('system', 'old_pager')) {
648                 $o .= alt_pager($a,count($r));
649         } else {
650                 $o .= paginate($a);
651         }
652
653         return $o;
654 }
655
656 /**
657  * @brief Returns posts from a given contact
658  *
659  * @param App $a argv application class
660  * @param int $contact_id contact
661  *
662  * @return string posts in HTML
663  */
664 function posts_from_contact($a, $contact_id) {
665
666         require_once('include/conversation.php');
667
668         $r = q("SELECT `url` FROM `contact` WHERE `id` = %d", intval($contact_id));
669         if (!$r)
670                 return false;
671
672         $contact = $r[0];
673
674         if(get_config('system', 'old_pager')) {
675                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
676                         WHERE `item`.`uid` = %d AND `author-link` IN ('%s', '%s')",
677                         intval(local_user()),
678                         dbesc(str_replace("https://", "http://", $contact["url"])),
679                         dbesc(str_replace("http://", "https://", $contact["url"])));
680
681                 $a->set_pager_total($r[0]['total']);
682         }
683
684         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
685                         `author-name` AS `name`, `owner-avatar` AS `photo`,
686                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
687                 FROM `item` FORCE INDEX (`uid_contactid_id`)
688                 WHERE `item`.`uid` = %d AND `contact-id` = %d
689                         AND `author-link` IN ('%s', '%s')
690                         AND NOT `deleted` AND NOT `moderated` AND `visible`
691                 ORDER BY `item`.`id` DESC LIMIT %d, %d",
692                 intval(local_user()),
693                 intval($contact_id),
694                 dbesc(str_replace("https://", "http://", $contact["url"])),
695                 dbesc(str_replace("http://", "https://", $contact["url"])),
696                 intval($a->pager['start']),
697                 intval($a->pager['itemspage'])
698         );
699
700         $o .= conversation($a,$r,'community',false);
701
702         if(!get_config('system', 'old_pager'))
703                 $o .= alt_pager($a,count($r));
704         else
705                 $o .= paginate($a);
706
707         return $o;
708 }
709
710 /**
711  * @brief Returns a formatted location string from the given profile array
712  *
713  * @param array $profile Profile array (Generated from the "profile" table)
714  *
715  * @return string Location string
716  */
717 function formatted_location($profile) {
718         $location = '';
719
720         if($profile['locality'])
721                 $location .= $profile['locality'];
722
723         if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
724                 if($location)
725                         $location .= ', ';
726
727                 $location .= $profile['region'];
728         }
729
730         if($profile['country-name']) {
731                 if($location)
732                         $location .= ', ';
733
734                 $location .= $profile['country-name'];
735         }
736
737         return $location;
738 }
739
740 /**
741  * @brief Returns the account type name
742  *
743  * The function can be called with either the user or the contact array
744  *
745  * @param array $contact contact or user array
746  */
747 function account_type($contact) {
748
749         // There are several fields that indicate that the contact or user is a forum
750         // "page-flags" is a field in the user table,
751         // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
752         // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
753         if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
754                 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
755                 || (isset($contact['forum']) && intval($contact['forum']))
756                 || (isset($contact['prv']) && intval($contact['prv']))
757                 || (isset($contact['community']) && intval($contact['community'])))
758                 $type = ACCOUNT_TYPE_COMMUNITY;
759         else
760                 $type = ACCOUNT_TYPE_PERSON;
761
762         // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
763         if (isset($contact["contact-type"]))
764                 $type = $contact["contact-type"];
765         if (isset($contact["account-type"]))
766                 $type = $contact["account-type"];
767
768         switch($type) {
769                 case ACCOUNT_TYPE_ORGANISATION:
770                         $account_type = t("Organisation");
771                         break;
772                 case ACCOUNT_TYPE_NEWS:
773                         $account_type = t('News');
774                         break;
775                 case ACCOUNT_TYPE_COMMUNITY:
776                         $account_type = t("Forum");
777                         break;
778                 default:
779                         $account_type = "";
780                         break;
781         }
782
783         return $account_type;
784 }
785 ?>