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