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