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