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