]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
1fcdc6951c1d79a85e9295bf3822194cb8b1ba1a
[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'] == '0000-00-00 00:00:00') {
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('0000-00-00 00:00:00'),
189                 intval($contact['id'])
190         );
191
192         if ($contact['url'] != '') {
193                 q("UPDATE `contact` SET `term-date` = '%s' WHERE `nurl` = '%s'",
194                         dbesc('0000-00-00 00:00:00'),
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"] != "0000-00-00") {
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"] = "0000-00-00";
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"] = "0000-00-00";
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         if (!$data['url']) {
581                 return 0;
582         }
583
584         $url = $data["url"];
585
586         // Does this address belongs to a valid network?
587         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA))) {
588                 if ($uid != 0) {
589                         return 0;
590                 }
591
592                 // Get data from the gcontact table
593                 $gcontacts = q("SELECT `name`, `nick`, `url`, `photo`, `addr`, `alias`, `network` FROM `gcontact` WHERE `nurl` = '%s'",
594                          dbesc(normalise_link($url)));
595                 if (!$gcontacts) {
596                         return 0;
597                 }
598
599                 $data = $gcontacts[0];
600         }
601
602
603         if (!$contact_id) {
604                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
605                                         `name`, `nick`, `photo`, `network`, `pubkey`, `rel`, `priority`,
606                                         `batch`, `request`, `confirm`, `poco`, `name-date`, `uri-date`,
607                                         `writable`, `blocked`, `readonly`, `pending`)
608                                         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)",
609                         intval($uid),
610                         dbesc(datetime_convert()),
611                         dbesc($data["url"]),
612                         dbesc(normalise_link($data["url"])),
613                         dbesc($data["addr"]),
614                         dbesc($data["alias"]),
615                         dbesc($data["notify"]),
616                         dbesc($data["poll"]),
617                         dbesc($data["name"]),
618                         dbesc($data["nick"]),
619                         dbesc($data["photo"]),
620                         dbesc($data["network"]),
621                         dbesc($data["pubkey"]),
622                         intval(CONTACT_IS_SHARING),
623                         intval($data["priority"]),
624                         dbesc($data["batch"]),
625                         dbesc($data["request"]),
626                         dbesc($data["confirm"]),
627                         dbesc($data["poco"]),
628                         dbesc(datetime_convert()),
629                         dbesc(datetime_convert())
630                 );
631
632                 $contacts = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
633                                 dbesc(normalise_link($data["url"])),
634                                 intval($uid));
635                 if (!dbm::is_result($contacts)) {
636                         return 0;
637                 }
638
639                 $contact_id = $contacts[0]["id"];
640
641                 // Update the newly created contact from data in the gcontact table
642                 $gcontacts = q("SELECT `location`, `about`, `keywords`, `gender` FROM `gcontact` WHERE `nurl` = '%s'",
643                          dbesc(normalise_link($data["url"])));
644                 if (dbm::is_result($gcontacts)) {
645                         logger("Update contact " . $data["url"] . ' from gcontact');
646                         q("UPDATE `contact` SET `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d",
647                                 dbesc($gcontacts[0]["location"]), dbesc($gcontacts[0]["about"]), dbesc($gcontacts[0]["keywords"]),
648                                 dbesc($gcontacts[0]["gender"]), intval($contact_id));
649                 }
650         }
651
652         if (count($contacts) > 1 AND $uid == 0 AND $contact_id != 0 AND $url != "") {
653                 q("DELETE FROM `contact` WHERE `nurl` = '%s' AND `id` != %d AND NOT `self`",
654                         dbesc(normalise_link($url)),
655                         intval($contact_id));
656         }
657
658         require_once "Photo.php";
659
660         update_contact_avatar($data["photo"], $uid, $contact_id);
661
662         $contacts = q("SELECT `addr`, `alias`, `name`, `nick` FROM `contact` WHERE `id` = %d", intval($contact_id));
663
664         // This condition should always be true
665         if (!dbm::is_result($contacts)) {
666                 return $contact_id;
667         }
668
669         // Only update if there had something been changed
670         if ($data["addr"] != $contacts[0]["addr"] OR
671                 $data["alias"] != $contacts[0]["alias"] OR
672                 $data["name"] != $contacts[0]["name"] OR
673                 $data["nick"] != $contacts[0]["nick"]) {
674                 q("UPDATE `contact` SET `addr` = '%s', `alias` = '%s', `name` = '%s', `nick` = '%s',
675                         `name-date` = '%s', `uri-date` = '%s' WHERE `id` = %d",
676                         dbesc($data["addr"]),
677                         dbesc($data["alias"]),
678                         dbesc($data["name"]),
679                         dbesc($data["nick"]),
680                         dbesc(datetime_convert()),
681                         dbesc(datetime_convert()),
682                         intval($contact_id)
683                 );
684         }
685
686         return $contact_id;
687 }
688
689 /**
690  * @brief Returns posts from a given gcontact
691  *
692  * @param App $a argv application class
693  * @param int $gcontact_id Global contact
694  *
695  * @return string posts in HTML
696  */
697 function posts_from_gcontact(App $a, $gcontact_id) {
698
699         require_once('include/conversation.php');
700
701         // There are no posts with "uid = 0" with connector networks
702         // This speeds up the query a lot
703         $r = q("SELECT `network` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
704         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
705                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
706         else
707                 $sql = "`item`.`uid` = %d";
708
709         if(get_config('system', 'old_pager')) {
710                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
711                         WHERE `gcontact-id` = %d and $sql",
712                         intval($gcontact_id),
713                         intval(local_user()));
714
715                 $a->set_pager_total($r[0]['total']);
716         }
717
718         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
719                         `author-name` AS `name`, `owner-avatar` AS `photo`,
720                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
721                 FROM `item`
722                 WHERE `gcontact-id` = %d AND $sql AND
723                         NOT `deleted` AND NOT `moderated` AND `visible`
724                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
725                 intval($gcontact_id),
726                 intval(local_user()),
727                 intval($a->pager['start']),
728                 intval($a->pager['itemspage'])
729         );
730
731         $o = conversation($a,$r,'community',false);
732
733         if(!get_config('system', 'old_pager')) {
734                 $o .= alt_pager($a,count($r));
735         } else {
736                 $o .= paginate($a);
737         }
738
739         return $o;
740 }
741 /**
742  * @brief Returns posts from a given contact url
743  *
744  * @param App $a argv application class
745  * @param string $contact_url Contact URL
746  *
747  * @return string posts in HTML
748  */
749 function posts_from_contact_url(App $a, $contact_url) {
750
751         require_once('include/conversation.php');
752
753         // There are no posts with "uid = 0" with connector networks
754         // This speeds up the query a lot
755         $r = q("SELECT `network`, `id` AS `author-id` FROM `contact`
756                 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
757                 dbesc(normalise_link($contact_url)));
758         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
759                 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND `item`.`private`))";
760         } else {
761                 $sql = "`item`.`uid` = %d";
762         }
763
764         if (!dbm::is_result($r)) {
765                 return '';
766         }
767
768         $author_id = intval($r[0]["author-id"]);
769
770         if (get_config('system', 'old_pager')) {
771                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
772                         WHERE `author-id` = %d and $sql",
773                         intval($author_id),
774                         intval(local_user()));
775
776                 $a->set_pager_total($r[0]['total']);
777         }
778
779         $r = q(item_query()." AND `item`.`author-id` = %d AND ".$sql.
780                 " ORDER BY `item`.`created` DESC LIMIT %d, %d",
781                 intval($author_id),
782                 intval(local_user()),
783                 intval($a->pager['start']),
784                 intval($a->pager['itemspage'])
785         );
786
787         $o = conversation($a,$r,'community',false);
788
789         if (!get_config('system', 'old_pager')) {
790                 $o .= alt_pager($a,count($r));
791         } else {
792                 $o .= paginate($a);
793         }
794
795         return $o;
796 }
797
798 /**
799  * @brief Returns a formatted location string from the given profile array
800  *
801  * @param array $profile Profile array (Generated from the "profile" table)
802  *
803  * @return string Location string
804  */
805 function formatted_location($profile) {
806         $location = '';
807
808         if($profile['locality'])
809                 $location .= $profile['locality'];
810
811         if($profile['region'] AND ($profile['locality'] != $profile['region'])) {
812                 if($location)
813                         $location .= ', ';
814
815                 $location .= $profile['region'];
816         }
817
818         if($profile['country-name']) {
819                 if($location)
820                         $location .= ', ';
821
822                 $location .= $profile['country-name'];
823         }
824
825         return $location;
826 }
827
828 /**
829  * @brief Returns the account type name
830  *
831  * The function can be called with either the user or the contact array
832  *
833  * @param array $contact contact or user array
834  */
835 function account_type($contact) {
836
837         // There are several fields that indicate that the contact or user is a forum
838         // "page-flags" is a field in the user table,
839         // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
840         // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
841         if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
842                 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
843                 || (isset($contact['forum']) && intval($contact['forum']))
844                 || (isset($contact['prv']) && intval($contact['prv']))
845                 || (isset($contact['community']) && intval($contact['community'])))
846                 $type = ACCOUNT_TYPE_COMMUNITY;
847         else
848                 $type = ACCOUNT_TYPE_PERSON;
849
850         // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
851         if (isset($contact["contact-type"]))
852                 $type = $contact["contact-type"];
853         if (isset($contact["account-type"]))
854                 $type = $contact["account-type"];
855
856         switch($type) {
857                 case ACCOUNT_TYPE_ORGANISATION:
858                         $account_type = t("Organisation");
859                         break;
860                 case ACCOUNT_TYPE_NEWS:
861                         $account_type = t('News');
862                         break;
863                 case ACCOUNT_TYPE_COMMUNITY:
864                         $account_type = t("Forum");
865                         break;
866                 default:
867                         $account_type = "";
868                         break;
869         }
870
871         return $account_type;
872 }
873 ?>