]> git.mxchange.org Git - friendica.git/blob - include/Contact.php
Merge pull request #3792 from annando/dead-contacts
[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' OR `archive`)",
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         $fields = array('term-date' => NULL_DATE, 'archive' => false);
170         dba::update('contact', $fields, array('id' => $contact['id']));
171
172         if ($contact['url'] != '') {
173                 dba::update('contact', $fields, array('nurl' => normalise_link($contact['url'])));
174         }
175 }
176
177 /**
178  * @brief Get contact data for a given profile link
179  *
180  * The function looks at several places (contact table and gcontact table) for the contact
181  * It caches its result for the same script execution to prevent duplicate calls
182  *
183  * @param string $url The profile link
184  * @param int $uid User id
185  * @param array $default If not data was found take this data as default value
186  *
187  * @return array Contact data
188  */
189 function get_contact_details_by_url($url, $uid = -1, $default = array()) {
190         static $cache = array();
191
192         if ($url == '') {
193                 return $default;
194         }
195
196         if ($uid == -1) {
197                 $uid = local_user();
198         }
199
200         if (isset($cache[$url][$uid])) {
201                 return $cache[$url][$uid];
202         }
203
204         $ssl_url = str_replace('http://', 'https://', $url);
205
206         // Fetch contact data from the contact table for the given user
207         $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`,
208                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
209                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?",
210                         normalise_link($url), $uid);
211         $r = dba::inArray($s);
212
213         // Fetch contact data from the contact table for the given user, checking with the alias
214         if (!dbm::is_result($r)) {
215                 $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`,
216                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
217                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?",
218                                 normalise_link($url), $url, $ssl_url, $uid);
219                 $r = dba::inArray($s);
220         }
221
222         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
223         if (!dbm::is_result($r)) {
224                 $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`,
225                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
226                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0",
227                                 normalise_link($url));
228                 $r = dba::inArray($s);
229         }
230
231         // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
232         if (!dbm::is_result($r)) {
233                 $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`,
234                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
235                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0",
236                                 normalise_link($url), $url, $ssl_url);
237                 $r = dba::inArray($s);
238         }
239
240         // Fetch the data from the gcontact table
241         if (!dbm::is_result($r)) {
242                 $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`,
243                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
244                         FROM `gcontact` WHERE `nurl` = ?",
245                                 normalise_link($url));
246                 $r = dba::inArray($s);
247         }
248
249         if (dbm::is_result($r)) {
250                 // If there is more than one entry we filter out the connector networks
251                 if (count($r) > 1) {
252                         foreach ($r AS $id => $result) {
253                                 if ($result["network"] == NETWORK_STATUSNET) {
254                                         unset($r[$id]);
255                                 }
256                         }
257                 }
258
259                 $profile = array_shift($r);
260
261                 // "bd" always contains the upcoming birthday of a contact.
262                 // "birthday" might contain the birthday including the year of birth.
263                 if ($profile["birthday"] > '0001-01-01') {
264                         $bd_timestamp = strtotime($profile["birthday"]);
265                         $month = date("m", $bd_timestamp);
266                         $day = date("d", $bd_timestamp);
267
268                         $current_timestamp = time();
269                         $current_year = date("Y", $current_timestamp);
270                         $current_month = date("m", $current_timestamp);
271                         $current_day = date("d", $current_timestamp);
272
273                         $profile["bd"] = $current_year."-".$month."-".$day;
274                         $current = $current_year."-".$current_month."-".$current_day;
275
276                         if ($profile["bd"] < $current) {
277                                 $profile["bd"] = (++$current_year)."-".$month."-".$day;
278                         }
279                 } else {
280                         $profile["bd"] = '0001-01-01';
281                 }
282         } else {
283                 $profile = $default;
284         }
285
286         if (($profile["photo"] == "") && isset($default["photo"])) {
287                 $profile["photo"] = $default["photo"];
288         }
289
290         if (($profile["name"] == "") && isset($default["name"])) {
291                 $profile["name"] = $default["name"];
292         }
293
294         if (($profile["network"] == "") && isset($default["network"])) {
295                 $profile["network"] = $default["network"];
296         }
297
298         if (($profile["thumb"] == "") && isset($profile["photo"])) {
299                 $profile["thumb"] = $profile["photo"];
300         }
301
302         if (($profile["micro"] == "") && isset($profile["thumb"])) {
303                 $profile["micro"] = $profile["thumb"];
304         }
305
306         if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0) &&
307                 in_array($profile["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS))) {
308                 proc_run(PRIORITY_LOW, "include/update_gcontact.php", $profile["gid"]);
309         }
310
311         // Show contact details of Diaspora contacts only if connected
312         if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
313                 $profile["location"] = "";
314                 $profile["about"] = "";
315                 $profile["gender"] = "";
316                 $profile["birthday"] = '0001-01-01';
317         }
318
319         $cache[$url][$uid] = $profile;
320
321         return $profile;
322 }
323
324 /**
325  * @brief Get contact data for a given address
326  *
327  * The function looks at several places (contact table and gcontact table) for the contact
328  *
329  * @param string $addr The profile link
330  * @param int $uid User id
331  *
332  * @return array Contact data
333  */
334 function get_contact_details_by_addr($addr, $uid = -1) {
335         static $cache = array();
336
337         if ($addr == '') {
338                 return array();
339         }
340
341         if ($uid == -1) {
342                 $uid = local_user();
343         }
344
345         // Fetch contact data from the contact table for the given user
346         $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
347                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
348                 FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
349                         dbesc($addr), intval($uid));
350
351         // Fetch the data from the contact table with "uid=0" (which is filled automatically)
352         if (!dbm::is_result($r))
353                 $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
354                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
355                         FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
356                                 dbesc($addr));
357
358         // Fetch the data from the gcontact table
359         if (!dbm::is_result($r))
360                 $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`,
361                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
362                         FROM `gcontact` WHERE `addr` = '%s'",
363                                 dbesc($addr));
364
365         if (!dbm::is_result($r)) {
366                 $data = Probe::uri($addr);
367
368                 $profile = get_contact_details_by_url($data['url'], $uid);
369         } else {
370                 $profile = $r[0];
371         }
372
373         return $profile;
374 }
375
376 if (! function_exists('contact_photo_menu')) {
377 function contact_photo_menu($contact, $uid = 0)
378 {
379         $a = get_app();
380
381         $contact_url = '';
382         $pm_url = '';
383         $status_link = '';
384         $photos_link = '';
385         $posts_link = '';
386         $contact_drop_link = '';
387         $poke_link = '';
388
389         if ($uid == 0) {
390                 $uid = local_user();
391         }
392
393         if ($contact['uid'] != $uid) {
394                 if ($uid == 0) {
395                         $profile_link = zrl($contact['url']);
396                         $menu = Array('profile' => array(t('View Profile'), $profile_link, true));
397
398                         return $menu;
399                 }
400
401                 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `network` = '%s' AND `uid` = %d",
402                         dbesc($contact['nurl']), dbesc($contact['network']), intval($uid));
403                 if ($r) {
404                         return contact_photo_menu($r[0], $uid);
405                 } else {
406                         $profile_link = zrl($contact['url']);
407                         $connlnk = 'follow/?url='.$contact['url'];
408                         $menu = array(
409                                 'profile' => array(t('View Profile'), $profile_link, true),
410                                 'follow' => array(t('Connect/Follow'), $connlnk, true)
411                         );
412
413                         return $menu;
414                 }
415         }
416
417         $sparkle = false;
418         if ($contact['network'] === NETWORK_DFRN) {
419                 $sparkle = true;
420                 $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
421         } else {
422                 $profile_link = $contact['url'];
423         }
424
425         if ($profile_link === 'mailbox') {
426                 $profile_link = '';
427         }
428
429         if ($sparkle) {
430                 $status_link = $profile_link . '?url=status';
431                 $photos_link = $profile_link . '?url=photos';
432                 $profile_link = $profile_link . '?url=profile';
433         }
434
435         if (in_array($contact['network'], array(NETWORK_DFRN, NETWORK_DIASPORA))) {
436                 $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
437         }
438
439         if ($contact['network'] == NETWORK_DFRN) {
440                 $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
441         }
442
443         $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
444
445         $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
446         $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
447
448         /**
449          * menu array:
450          * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
451          */
452         $menu = array(
453                 'status' => array(t("View Status"), $status_link, true),
454                 'profile' => array(t("View Profile"), $profile_link, true),
455                 'photos' => array(t("View Photos"), $photos_link, true),
456                 'network' => array(t("Network Posts"), $posts_link, false),
457                 'edit' => array(t("View Contact"), $contact_url, false),
458                 'drop' => array(t("Drop Contact"), $contact_drop_link, false),
459                 'pm' => array(t("Send PM"), $pm_url, false),
460                 'poke' => array(t("Poke"), $poke_link, false),
461         );
462
463
464         $args = array('contact' => $contact, 'menu' => &$menu);
465
466         call_hooks('contact_photo_menu', $args);
467
468         $menucondensed = array();
469
470         foreach ($menu AS $menuname => $menuitem) {
471                 if ($menuitem[1] != '') {
472                         $menucondensed[$menuname] = $menuitem;
473                 }
474         }
475
476         return $menucondensed;
477 }}
478
479
480 function random_profile() {
481         $r = q("SELECT `url` FROM `gcontact` WHERE `network` = '%s'
482                                 AND `last_contact` >= `last_failure`
483                                 AND `updated` > UTC_TIMESTAMP - INTERVAL 1 MONTH
484                         ORDER BY rand() LIMIT 1",
485                 dbesc(NETWORK_DFRN));
486
487         if (dbm::is_result($r))
488                 return dirname($r[0]['url']);
489         return '';
490 }
491
492
493 function contacts_not_grouped($uid,$start = 0,$count = 0) {
494
495         if(! $count) {
496                 $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) ",
497                         intval($uid),
498                         intval($uid)
499                 );
500
501                 return $r;
502
503
504         }
505
506         $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",
507                 intval($uid),
508                 intval($uid),
509                 intval($start),
510                 intval($count)
511         );
512
513         return $r;
514 }
515
516 /**
517  * @brief Fetch the contact id for a given url and user
518  *
519  * First lookup in the contact table to find a record matching either `url`, `nurl`,
520  * `addr` or `alias`.
521  *
522  * If there's no record and we aren't looking for a public contact, we quit.
523  * If there's one, we check that it isn't time to update the picture else we
524  * directly return the found contact id.
525  *
526  * Second, we probe the provided $url wether it's http://server.tld/profile or
527  * nick@server.tld. We quit if we can't get any info back.
528  *
529  * Third, we create the contact record if it doesn't exist
530  *
531  * Fourth, we update the existing record with the new data (avatar, alias, nick)
532  * if there's any updates
533  *
534  * @param string $url Contact URL
535  * @param integer $uid The user id for the contact (0 = public contact)
536  * @param boolean $no_update Don't update the contact
537  *
538  * @return integer Contact ID
539  */
540 function get_contact($url, $uid = 0, $no_update = false) {
541         logger("Get contact data for url ".$url." and user ".$uid." - ".System::callstack(), LOGGER_DEBUG);
542
543         $data = array();
544         $contact_id = 0;
545
546         if ($url == '') {
547                 return 0;
548         }
549
550         // We first try the nurl (http://server.tld/nick), most common case
551         $contact = dba::select('contact', array('id', 'avatar-date'), array('nurl' => normalise_link($url), 'uid' => $uid), array('limit' => 1));
552
553         // Then the addr (nick@server.tld)
554         if (!dbm::is_result($contact)) {
555                 $contact = dba::select('contact', array('id', 'avatar-date'), array('addr' => $url, 'uid' => $uid), array('limit' => 1));
556         }
557
558         // Then the alias (which could be anything)
559         if (!dbm::is_result($contact)) {
560                 // The link could be provided as http although we stored it as https
561                 $ssl_url = str_replace('http://', 'https://', $url);
562                 $r = dba::p("SELECT `id`, `avatar-date` FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ? LIMIT 1",
563                                 $url, normalise_link($url), $ssl_url, $uid);
564                 $contact = dba::fetch($r);
565                 dba::close($r);
566         }
567
568         if (dbm::is_result($contact)) {
569                 $contact_id = $contact["id"];
570
571                 // Update the contact every 7 days
572                 $update_contact = ($contact['avatar-date'] < datetime_convert('','','now -7 days'));
573
574                 // We force the update if the avatar is empty
575                 if ($contact['avatar'] == '') {
576                         $update_contact = true;
577                 }
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, "", $uid);
588
589         // Last try in gcontact for unsupported networks
590         if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
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         if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
606                 $contact_id = get_contact($data["alias"], $uid, true);
607         }
608
609         $url = $data["url"];
610         if (!$contact_id) {
611                 dba::insert('contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
612                                         'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
613                                         'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
614                                         'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
615                                         'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
616                                         'network' => $data["network"], 'pubkey' => $data["pubkey"],
617                                         'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
618                                         'batch' => $data["batch"], 'request' => $data["request"],
619                                         'confirm' => $data["confirm"], 'poco' => $data["poco"],
620                                         'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
621                                         'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
622                                         'readonly' => 0, 'pending' => 0));
623
624                 $contacts = q("SELECT `id` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d ORDER BY `id` LIMIT 2",
625                                 dbesc(normalise_link($data["url"])),
626                                 intval($uid));
627                 if (!dbm::is_result($contacts)) {
628                         return 0;
629                 }
630
631                 $contact_id = $contacts[0]["id"];
632
633                 // Update the newly created contact from data in the gcontact table
634                 $gcontact = dba::select('gcontact', array('location', 'about', 'keywords', 'gender'),
635                                         array('nurl' => normalise_link($data["url"])), array('limit' => 1));
636                 if (dbm::is_result($gcontact)) {
637                         // Only use the information when the probing hadn't fetched these values
638                         if ($data['keywords'] != '') {
639                                 unset($gcontact['keywords']);
640                         }
641                         if ($data['location'] != '') {
642                                 unset($gcontact['location']);
643                         }
644                         if ($data['about'] != '') {
645                                 unset($gcontact['about']);
646                         }
647                         dba::update('contact', $gcontact, array('id' => $contact_id));
648                 }
649
650                 if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
651                         dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
652                                 normalise_link($data["url"]), $contact_id));
653                 }
654         }
655
656         require_once "Photo.php";
657
658         update_contact_avatar($data["photo"], $uid, $contact_id);
659
660         $contact = dba::select('contact', array('url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date'),
661                                 array('id' => $contact_id), array('limit' => 1));
662
663         // This condition should always be true
664         if (!dbm::is_result($contact)) {
665                 return $contact_id;
666         }
667
668         $updated = array('addr' => $data['addr'],
669                         'alias' => $data['alias'],
670                         'url' => $data['url'],
671                         'nurl' => normalise_link($data['url']),
672                         'name' => $data['name'],
673                         'nick' => $data['nick']);
674
675         if ($data['keywords'] != '') {
676                 $updated['keywords'] = $data['keywords'];
677         }
678         if ($data['location'] != '') {
679                 $updated['location'] = $data['location'];
680         }
681         if ($data['about'] != '') {
682                 $updated['about'] = $data['about'];
683         }
684
685         if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
686                 $updated['uri-date'] = datetime_convert();
687         }
688         if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
689                 $updated['name-date'] = datetime_convert();
690         }
691
692         $updated['avatar-date'] = datetime_convert();
693
694         dba::update('contact', $updated, array('id' => $contact_id), $contact);
695
696         return $contact_id;
697 }
698
699 /**
700  * @brief Checks if the contact is blocked
701  *
702  * @param int $cid contact id
703  *
704  * @return boolean Is the contact blocked?
705  */
706 function blockedContact($cid) {
707         if ($cid == 0) {
708                 return false;
709         }
710
711         $blocked = dba::select('contact', array('blocked'), array('id' => $cid), array('limit' => 1));
712         if (!dbm::is_result($blocked)) {
713                 return false;
714         }
715         return (bool)$blocked['blocked'];
716 }
717
718 /**
719  * @brief Checks if the contact is hidden
720  *
721  * @param int $cid contact id
722  *
723  * @return boolean Is the contact hidden?
724  */
725 function hiddenContact($cid) {
726         if ($cid == 0) {
727                 return false;
728         }
729
730         $hidden = dba::select('contact', array('hidden'), array('id' => $cid), array('limit' => 1));
731         if (!dbm::is_result($hidden)) {
732                 return false;
733         }
734         return (bool)$hidden['hidden'];
735 }
736
737 /**
738  * @brief Returns posts from a given gcontact
739  *
740  * @param App $a argv application class
741  * @param int $gcontact_id Global contact
742  *
743  * @return string posts in HTML
744  */
745 function posts_from_gcontact(App $a, $gcontact_id) {
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` FROM `gcontact` WHERE `id` = %d", dbesc($gcontact_id));
752         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, "")))
753                 $sql = "(`item`.`uid` = 0 OR  (`item`.`uid` = %d AND `item`.`private`))";
754         else
755                 $sql = "`item`.`uid` = %d";
756
757         $r = q("SELECT `item`.`uri`, `item`.*, `item`.`id` AS `item_id`,
758                         `author-name` AS `name`, `owner-avatar` AS `photo`,
759                         `owner-link` AS `url`, `owner-avatar` AS `thumb`
760                 FROM `item`
761                 WHERE `gcontact-id` = %d AND $sql AND
762                         NOT `deleted` AND NOT `moderated` AND `visible`
763                 ORDER BY `item`.`created` DESC LIMIT %d, %d",
764                 intval($gcontact_id),
765                 intval(local_user()),
766                 intval($a->pager['start']),
767                 intval($a->pager['itemspage'])
768         );
769
770         $o = conversation($a, $r, 'community', false);
771
772         $o .= alt_pager($a, count($r));
773
774         return $o;
775 }
776 /**
777  * @brief Returns posts from a given contact url
778  *
779  * @param App $a argv application class
780  * @param string $contact_url Contact URL
781  *
782  * @return string posts in HTML
783  */
784 function posts_from_contact_url(App $a, $contact_url) {
785
786         require_once 'include/conversation.php';
787
788         // There are no posts with "uid = 0" with connector networks
789         // This speeds up the query a lot
790         $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
791                 WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
792                 dbesc(normalise_link($contact_url)));
793
794         if (!dbm::is_result($r)) {
795                 return '';
796         }
797
798         if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
799                 $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
800         } else {
801                 $sql = "`item`.`uid` = %d";
802         }
803
804         $author_id = intval($r[0]["author-id"]);
805
806         $contact = ($r[0]["contact-type"] = ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
807
808         $r = q(item_query()." AND `item`.`".$contact."` = %d AND ".$sql.
809                 " ORDER BY `item`.`created` DESC LIMIT %d, %d",
810                 intval($author_id),
811                 intval(local_user()),
812                 intval($a->pager['start']),
813                 intval($a->pager['itemspage'])
814         );
815
816         $o = conversation($a, $r, 'community', false);
817
818         $o .= alt_pager($a, count($r));
819
820         return $o;
821 }
822
823 /**
824  * @brief Returns a formatted location string from the given profile array
825  *
826  * @param array $profile Profile array (Generated from the "profile" table)
827  *
828  * @return string Location string
829  */
830 function formatted_location($profile) {
831         $location = '';
832
833         if($profile['locality'])
834                 $location .= $profile['locality'];
835
836         if($profile['region'] && ($profile['locality'] != $profile['region'])) {
837                 if($location)
838                         $location .= ', ';
839
840                 $location .= $profile['region'];
841         }
842
843         if($profile['country-name']) {
844                 if($location)
845                         $location .= ', ';
846
847                 $location .= $profile['country-name'];
848         }
849
850         return $location;
851 }
852
853 /**
854  * @brief Returns the account type name
855  *
856  * The function can be called with either the user or the contact array
857  *
858  * @param array $contact contact or user array
859  */
860 function account_type($contact) {
861
862         // There are several fields that indicate that the contact or user is a forum
863         // "page-flags" is a field in the user table,
864         // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
865         // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
866         if((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
867                 || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
868                 || (isset($contact['forum']) && intval($contact['forum']))
869                 || (isset($contact['prv']) && intval($contact['prv']))
870                 || (isset($contact['community']) && intval($contact['community'])))
871                 $type = ACCOUNT_TYPE_COMMUNITY;
872         else
873                 $type = ACCOUNT_TYPE_PERSON;
874
875         // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
876         if (isset($contact["contact-type"]))
877                 $type = $contact["contact-type"];
878         if (isset($contact["account-type"]))
879                 $type = $contact["account-type"];
880
881         switch($type) {
882                 case ACCOUNT_TYPE_ORGANISATION:
883                         $account_type = t("Organisation");
884                         break;
885                 case ACCOUNT_TYPE_NEWS:
886                         $account_type = t('News');
887                         break;
888                 case ACCOUNT_TYPE_COMMUNITY:
889                         $account_type = t("Forum");
890                         break;
891                 default:
892                         $account_type = "";
893                         break;
894         }
895
896         return $account_type;
897 }