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