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