]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
2778e8a5d636669dbae0e3f4ab5876cccb85e44c
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @file src/Model/Contact.php
4  */
5 namespace Friendica\Model;
6
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\PConfig;
11 use Friendica\Core\System;
12 use Friendica\Core\Worker;
13 use Friendica\Database\DBM;
14 use Friendica\Network\Probe;
15 use Friendica\Model\Photo;
16 use Friendica\Model\Profile;
17 use Friendica\Protocol\Diaspora;
18 use Friendica\Protocol\DFRN;
19 use Friendica\Protocol\OStatus;
20 use Friendica\Protocol\PortableContact;
21 use Friendica\Protocol\Salmon;
22 use dba;
23
24 require_once 'boot.php';
25 require_once 'include/dba.php';
26 require_once 'include/text.php';
27
28 /**
29  * @brief functions for interacting with a contact
30  */
31 class Contact extends BaseObject
32 {
33         /**
34          * @brief Returns a list of contacts belonging in a group
35          *
36          * @param int $gid
37          * @return array
38          */
39         public static function getByGroupId($gid)
40         {
41                 $return = [];
42                 if (intval($gid)) {
43                         $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
44                                 FROM `contact`
45                                 INNER JOIN `group_member`
46                                         ON `contact`.`id` = `group_member`.`contact-id`
47                                 WHERE `gid` = ?
48                                 AND `contact`.`uid` = ?
49                                 AND NOT `contact`.`self`
50                                 AND NOT `contact`.`blocked`
51                                 AND NOT `contact`.`pending`
52                                 ORDER BY `contact`.`name` ASC',
53                                 $gid,
54                                 local_user()
55                         );
56                         if (DBM::is_result($stmt)) {
57                                 $return = dba::inArray($stmt);
58                         }
59                 }
60
61                 return $return;
62         }
63
64         /**
65          * @brief Returns the count of OStatus contacts in a group
66          *
67          * @param int $gid
68          * @return int
69          */
70         public static function getOStatusCountByGroupId($gid)
71         {
72                 $return = 0;
73                 if (intval($gid)) {
74                         $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
75                                 FROM `contact`
76                                 INNER JOIN `group_member`
77                                         ON `contact`.`id` = `group_member`.`contact-id`
78                                 WHERE `gid` = ?
79                                 AND `contact`.`uid` = ?
80                                 AND `contact`.`network` = ?
81                                 AND `contact`.`notify` != ""',
82                                 $gid,
83                                 local_user(),
84                                 NETWORK_OSTATUS
85                         );
86                         $return = $contacts['count'];
87                 }
88
89                 return $return;
90         }
91
92         /**
93          * Creates the self-contact for the provided user id
94          *
95          * @param int $uid
96          * @return bool Operation success
97          */
98         public static function createSelfFromUserId($uid)
99         {
100                 // Only create the entry if it doesn't exist yet
101                 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
102                         return true;
103                 }
104
105                 $user = dba::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
106                 if (!DBM::is_result($user)) {
107                         return false;
108                 }
109
110                 $return = dba::insert('contact', [
111                         'uid'         => $user['uid'],
112                         'created'     => datetime_convert(),
113                         'self'        => 1,
114                         'name'        => $user['username'],
115                         'nick'        => $user['nickname'],
116                         'photo'       => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
117                         'thumb'       => System::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
118                         'micro'       => System::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
119                         'blocked'     => 0,
120                         'pending'     => 0,
121                         'url'         => System::baseUrl() . '/profile/' . $user['nickname'],
122                         'nurl'        => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
123                         'addr'        => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
124                         'request'     => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
125                         'notify'      => System::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
126                         'poll'        => System::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
127                         'confirm'     => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
128                         'poco'        => System::baseUrl() . '/poco/'         . $user['nickname'],
129                         'name-date'   => datetime_convert(),
130                         'uri-date'    => datetime_convert(),
131                         'avatar-date' => datetime_convert(),
132                         'closeness'   => 0
133                 ]);
134
135                 return $return;
136         }
137
138         /**
139          * @brief Marks a contact for removal
140          *
141          * @param int $id contact id
142          * @return null
143          */
144         public static function remove($id)
145         {
146                 // We want just to make sure that we don't delete our "self" contact
147                 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
148                 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
149                         return;
150                 }
151
152                 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
153                 if ($archive) {
154                         dba::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
155                         return;
156                 }
157
158                 dba::delete('contact', ['id' => $id]);
159
160                 // Delete the rest in the background
161                 Worker::add(PRIORITY_LOW, 'RemoveContact', $id);
162         }
163
164         /**
165          * @brief Sends an unfriend message. Does not remove the contact
166          *
167          * @param array $user    User unfriending
168          * @param array $contact Contact unfriended
169          * @return void
170          */
171         public static function terminateFriendship(array $user, array $contact)
172         {
173                 if ($contact['network'] === NETWORK_OSTATUS) {
174                         // create an unfollow slap
175                         $item = [];
176                         $item['verb'] = NAMESPACE_OSTATUS . "/unfollow";
177                         $item['follow'] = $contact["url"];
178                         $slap = OStatus::salmon($item, $user);
179
180                         if ((x($contact, 'notify')) && (strlen($contact['notify']))) {
181                                 Salmon::slapper($user, $contact['notify'], $slap);
182                         }
183                 } elseif ($contact['network'] === NETWORK_DIASPORA) {
184                         Diaspora::sendUnshare($user, $contact);
185                 } elseif ($contact['network'] === NETWORK_DFRN) {
186                         DFRN::deliver($user, $contact, 'placeholder', 1);
187                 }
188         }
189
190         /**
191          * @brief Marks a contact for archival after a communication issue delay
192          *
193          * Contact has refused to recognise us as a friend. We will start a countdown.
194          * If they still don't recognise us in 32 days, the relationship is over,
195          * and we won't waste any more time trying to communicate with them.
196          * This provides for the possibility that their database is temporarily messed
197          * up or some other transient event and that there's a possibility we could recover from it.
198          *
199          * @param array $contact contact to mark for archival
200          * @return null
201          */
202         public static function markForArchival(array $contact)
203         {
204                 // Contact already archived or "self" contact? => nothing to do
205                 if ($contact['archive'] || $contact['self']) {
206                         return;
207                 }
208
209                 if ($contact['term-date'] <= NULL_DATE) {
210                         dba::update('contact', ['term-date' => datetime_convert()], ['id' => $contact['id']]);
211
212                         if ($contact['url'] != '') {
213                                 dba::update('contact', ['term-date' => datetime_convert()], ['`nurl` = ? AND `term-date` <= ? AND NOT `self`', normalise_link($contact['url']), NULL_DATE]);
214                         }
215                 } else {
216                         /* @todo
217                          * We really should send a notification to the owner after 2-3 weeks
218                          * so they won't be surprised when the contact vanishes and can take
219                          * remedial action if this was a serious mistake or glitch
220                          */
221
222                         /// @todo Check for contact vitality via probing
223                         $expiry = $contact['term-date'] . ' + 32 days ';
224                         if (datetime_convert() > datetime_convert('UTC', 'UTC', $expiry)) {
225                                 /* Relationship is really truly dead. archive them rather than
226                                  * delete, though if the owner tries to unarchive them we'll start
227                                  * the whole process over again.
228                                  */
229                                 dba::update('contact', ['archive' => 1], ['id' => $contact['id']]);
230
231                                 if ($contact['url'] != '') {
232                                         dba::update('contact', ['archive' => 1], ['nurl' => normalise_link($contact['url']), 'self' => false]);
233                                 }
234                         }
235                 }
236         }
237
238         /**
239          * @brief Cancels the archival countdown
240          *
241          * @see Contact::markForArchival()
242          *
243          * @param array $contact contact to be unmarked for archival
244          * @return null
245          */
246         public static function unmarkForArchival(array $contact)
247         {
248                 $condition = ['`id` = ? AND (`term-date` > ? OR `archive`)', $contact['id'], NULL_DATE];
249                 $exists = dba::exists('contact', $condition);
250
251                 // We don't need to update, we never marked this contact for archival
252                 if (!$exists) {
253                         return;
254                 }
255
256                 // It's a miracle. Our dead contact has inexplicably come back to life.
257                 $fields = ['term-date' => NULL_DATE, 'archive' => false];
258                 dba::update('contact', $fields, ['id' => $contact['id']]);
259
260                 if ($contact['url'] != '') {
261                         dba::update('contact', $fields, ['nurl' => normalise_link($contact['url'])]);
262                 }
263         }
264
265         /**
266          * @brief Get contact data for a given profile link
267          *
268          * The function looks at several places (contact table and gcontact table) for the contact
269          * It caches its result for the same script execution to prevent duplicate calls
270          *
271          * @param string $url     The profile link
272          * @param int    $uid     User id
273          * @param array  $default If not data was found take this data as default value
274          *
275          * @return array Contact data
276          */
277         public static function getDetailsByURL($url, $uid = -1, array $default = [])
278         {
279                 static $cache = [];
280
281                 if ($url == '') {
282                         return $default;
283                 }
284
285                 if ($uid == -1) {
286                         $uid = local_user();
287                 }
288
289                 if (isset($cache[$url][$uid])) {
290                         return $cache[$url][$uid];
291                 }
292
293                 $ssl_url = str_replace('http://', 'https://', $url);
294
295                 // Fetch contact data from the contact table for the given user
296                 $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`,
297                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
298                 FROM `contact` WHERE `nurl` = ? AND `uid` = ?", normalise_link($url), $uid);
299                 $r = dba::inArray($s);
300
301                 // Fetch contact data from the contact table for the given user, checking with the alias
302                 if (!DBM::is_result($r)) {
303                         $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`,
304                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
305                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = ?", normalise_link($url), $url, $ssl_url, $uid);
306                         $r = dba::inArray($s);
307                 }
308
309                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
310                 if (!DBM::is_result($r)) {
311                         $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`,
312                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
313                         FROM `contact` WHERE `nurl` = ? AND `uid` = 0", normalise_link($url));
314                         $r = dba::inArray($s);
315                 }
316
317                 // Fetch the data from the contact table with "uid=0" (which is filled automatically) - checked with the alias
318                 if (!DBM::is_result($r)) {
319                         $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`,
320                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
321                         FROM `contact` WHERE `alias` IN (?, ?, ?) AND `uid` = 0", normalise_link($url), $url, $ssl_url);
322                         $r = dba::inArray($s);
323                 }
324
325                 // Fetch the data from the gcontact table
326                 if (!DBM::is_result($r)) {
327                         $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`,
328                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
329                         FROM `gcontact` WHERE `nurl` = ?", normalise_link($url));
330                         $r = dba::inArray($s);
331                 }
332
333                 if (DBM::is_result($r)) {
334                         // If there is more than one entry we filter out the connector networks
335                         if (count($r) > 1) {
336                                 foreach ($r as $id => $result) {
337                                         if ($result["network"] == NETWORK_STATUSNET) {
338                                                 unset($r[$id]);
339                                         }
340                                 }
341                         }
342
343                         $profile = array_shift($r);
344
345                         // "bd" always contains the upcoming birthday of a contact.
346                         // "birthday" might contain the birthday including the year of birth.
347                         if ($profile["birthday"] > '0001-01-01') {
348                                 $bd_timestamp = strtotime($profile["birthday"]);
349                                 $month = date("m", $bd_timestamp);
350                                 $day = date("d", $bd_timestamp);
351
352                                 $current_timestamp = time();
353                                 $current_year = date("Y", $current_timestamp);
354                                 $current_month = date("m", $current_timestamp);
355                                 $current_day = date("d", $current_timestamp);
356
357                                 $profile["bd"] = $current_year . "-" . $month . "-" . $day;
358                                 $current = $current_year . "-" . $current_month . "-" . $current_day;
359
360                                 if ($profile["bd"] < $current) {
361                                         $profile["bd"] = ( ++$current_year) . "-" . $month . "-" . $day;
362                                 }
363                         } else {
364                                 $profile["bd"] = '0001-01-01';
365                         }
366                 } else {
367                         $profile = $default;
368                 }
369
370                 if (($profile["photo"] == "") && isset($default["photo"])) {
371                         $profile["photo"] = $default["photo"];
372                 }
373
374                 if (($profile["name"] == "") && isset($default["name"])) {
375                         $profile["name"] = $default["name"];
376                 }
377
378                 if (($profile["network"] == "") && isset($default["network"])) {
379                         $profile["network"] = $default["network"];
380                 }
381
382                 if (($profile["thumb"] == "") && isset($profile["photo"])) {
383                         $profile["thumb"] = $profile["photo"];
384                 }
385
386                 if (($profile["micro"] == "") && isset($profile["thumb"])) {
387                         $profile["micro"] = $profile["thumb"];
388                 }
389
390                 if ((($profile["addr"] == "") || ($profile["name"] == "")) && ($profile["gid"] != 0)
391                         && in_array($profile["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS])
392                 ) {
393                         Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
394                 }
395
396                 // Show contact details of Diaspora contacts only if connected
397                 if (($profile["cid"] == 0) && ($profile["network"] == NETWORK_DIASPORA)) {
398                         $profile["location"] = "";
399                         $profile["about"] = "";
400                         $profile["gender"] = "";
401                         $profile["birthday"] = '0001-01-01';
402                 }
403
404                 $cache[$url][$uid] = $profile;
405
406                 return $profile;
407         }
408
409         /**
410          * @brief Get contact data for a given address
411          *
412          * The function looks at several places (contact table and gcontact table) for the contact
413          *
414          * @param string $addr The profile link
415          * @param int    $uid  User id
416          *
417          * @return array Contact data
418          */
419         public static function getDetailsByAddr($addr, $uid = -1)
420         {
421                 static $cache = [];
422
423                 if ($addr == '') {
424                         return [];
425                 }
426
427                 if ($uid == -1) {
428                         $uid = local_user();
429                 }
430
431                 // Fetch contact data from the contact table for the given user
432                 $r = q("SELECT `id`, `id` AS `cid`, 0 AS `gid`, 0 AS `zid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
433                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, `self`
434                         FROM `contact` WHERE `addr` = '%s' AND `uid` = %d",
435                         dbesc($addr),
436                         intval($uid)
437                 );
438                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
439                 if (!DBM::is_result($r)) {
440                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
441                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
442                                 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
443                                 dbesc($addr)
444                         );
445                 }
446
447                 // Fetch the data from the gcontact table
448                 if (!DBM::is_result($r)) {
449                         $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`,
450                                 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
451                                 FROM `gcontact` WHERE `addr` = '%s'",
452                                 dbesc($addr)
453                         );
454                 }
455
456                 if (!DBM::is_result($r)) {
457                         $data = Probe::uri($addr);
458
459                         $profile = self::getDetailsByURL($data['url'], $uid);
460                 } else {
461                         $profile = $r[0];
462                 }
463
464                 return $profile;
465         }
466
467         /**
468          * @brief Returns the data array for the photo menu of a given contact
469          *
470          * @param array $contact contact
471          * @param int   $uid     optional, default 0
472          * @return array
473          */
474         public static function photoMenu(array $contact, $uid = 0)
475         {
476                 // @todo Unused, to be removed
477                 $a = get_app();
478
479                 $contact_url = '';
480                 $pm_url = '';
481                 $status_link = '';
482                 $photos_link = '';
483                 $posts_link = '';
484                 $contact_drop_link = '';
485                 $poke_link = '';
486
487                 if ($uid == 0) {
488                         $uid = local_user();
489                 }
490
491                 if ($contact['uid'] != $uid) {
492                         if ($uid == 0) {
493                                 $profile_link = Profile::zrl($contact['url']);
494                                 $menu = ['profile' => [t('View Profile'), $profile_link, true]];
495
496                                 return $menu;
497                         }
498
499                         // Look for our own contact if the uid doesn't match and isn't public
500                         $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
501                         if (DBM::is_result($contact_own)) {
502                                 return self::photoMenu($contact_own, $uid);
503                         } else {
504                                 $profile_link = Profile::zrl($contact['url']);
505                                 $connlnk = 'follow/?url=' . $contact['url'];
506                                 $menu = [
507                                         'profile' => [t('View Profile'), $profile_link, true],
508                                         'follow' => [t('Connect/Follow'), $connlnk, true]
509                                 ];
510
511                                 return $menu;
512                         }
513                 }
514
515                 $sparkle = false;
516                 if ($contact['network'] === NETWORK_DFRN) {
517                         $sparkle = true;
518                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
519                 } else {
520                         $profile_link = $contact['url'];
521                 }
522
523                 if ($profile_link === 'mailbox') {
524                         $profile_link = '';
525                 }
526
527                 if ($sparkle) {
528                         $status_link = $profile_link . '?url=status';
529                         $photos_link = $profile_link . '?url=photos';
530                         $profile_link = $profile_link . '?url=profile';
531                 }
532
533                 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
534                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
535                 }
536
537                 if ($contact['network'] == NETWORK_DFRN) {
538                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
539                 }
540
541                 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
542
543                 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
544                 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
545
546                 /**
547                  * Menu array:
548                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
549                  */
550                 $menu = [
551                         'status'  => [t("View Status")  , $status_link      , true],
552                         'profile' => [t("View Profile") , $profile_link     , true],
553                         'photos'  => [t("View Photos")  , $photos_link      , true],
554                         'network' => [t("Network Posts"), $posts_link       , false],
555                         'edit'    => [t("View Contact") , $contact_url      , false],
556                         'drop'    => [t("Drop Contact") , $contact_drop_link, false],
557                         'pm'      => [t("Send PM")      , $pm_url           , false],
558                         'poke'    => [t("Poke")         , $poke_link        , false],
559                 ];
560
561                 $args = ['contact' => $contact, 'menu' => &$menu];
562
563                 Addon::callHooks('contact_photo_menu', $args);
564
565                 $menucondensed = [];
566
567                 foreach ($menu as $menuname => $menuitem) {
568                         if ($menuitem[1] != '') {
569                                 $menucondensed[$menuname] = $menuitem;
570                         }
571                 }
572
573                 return $menucondensed;
574         }
575
576         /**
577          * @brief Returns ungrouped contact count or list for user
578          *
579          * Returns either the total number of ungrouped contacts for the given user
580          * id or a paginated list of ungrouped contacts.
581          *
582          * @param int $uid   uid
583          * @param int $start optional, default 0
584          * @param int $count optional, default 0
585          *
586          * @return array
587          */
588         public static function getUngroupedList($uid, $start = 0, $count = 0)
589         {
590                 if (!$count) {
591                         $r = q(
592                                 "SELECT COUNT(*) AS `total`
593                                  FROM `contact`
594                                  WHERE `uid` = %d
595                                  AND NOT `self`
596                                  AND NOT `blocked`
597                                  AND NOT `pending`
598                                  AND `id` NOT IN (
599                                         SELECT DISTINCT(`contact-id`)
600                                         FROM `group_member`
601                                         WHERE `uid` = %d
602                                 )",
603                                 intval($uid),
604                                 intval($uid)
605                         );
606
607                         return $r;
608                 }
609
610                 $r = q(
611                         "SELECT *
612                         FROM `contact`
613                         WHERE `uid` = %d
614                         AND NOT `self`
615                         AND NOT `blocked`
616                         AND NOT `pending`
617                         AND `id` NOT IN (
618                                 SELECT DISTINCT(`contact-id`)
619                                 FROM `group_member`
620                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
621                                 WHERE `group`.`uid` = %d
622                         )
623                         LIMIT %d, %d",
624                         intval($uid),
625                         intval($uid),
626                         intval($start),
627                         intval($count)
628                 );
629
630                 return $r;
631         }
632
633         /**
634          * @brief Fetch the contact id for a given URL and user
635          *
636          * First lookup in the contact table to find a record matching either `url`, `nurl`,
637          * `addr` or `alias`.
638          *
639          * If there's no record and we aren't looking for a public contact, we quit.
640          * If there's one, we check that it isn't time to update the picture else we
641          * directly return the found contact id.
642          *
643          * Second, we probe the provided $url whether it's http://server.tld/profile or
644          * nick@server.tld. We quit if we can't get any info back.
645          *
646          * Third, we create the contact record if it doesn't exist
647          *
648          * Fourth, we update the existing record with the new data (avatar, alias, nick)
649          * if there's any updates
650          *
651          * @param string  $url       Contact URL
652          * @param integer $uid       The user id for the contact (0 = public contact)
653          * @param boolean $no_update Don't update the contact
654          *
655          * @return integer Contact ID
656          */
657         public static function getIdForURL($url, $uid = 0, $no_update = false)
658         {
659                 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
660
661                 $contact_id = 0;
662
663                 if ($url == '') {
664                         return 0;
665                 }
666
667                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
668                 // We first try the nurl (http://server.tld/nick), most common case
669                 $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
670
671                 // Then the addr (nick@server.tld)
672                 if (!DBM::is_result($contact)) {
673                         $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
674                 }
675
676                 // Then the alias (which could be anything)
677                 if (!DBM::is_result($contact)) {
678                         // The link could be provided as http although we stored it as https
679                         $ssl_url = str_replace('http://', 'https://', $url);
680                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
681                         $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
682                 }
683
684                 if (DBM::is_result($contact)) {
685                         $contact_id = $contact["id"];
686
687                         // Update the contact every 7 days
688                         $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
689
690                         // We force the update if the avatar is empty
691                         if (!x($contact, 'avatar')) {
692                                 $update_contact = true;
693                         }
694
695                         if (!$update_contact || $no_update) {
696                                 return $contact_id;
697                         }
698                 } elseif ($uid != 0) {
699                         // Non-existing user-specific contact, exiting
700                         return 0;
701                 }
702
703                 $data = Probe::uri($url, "", $uid);
704
705                 // Last try in gcontact for unsupported networks
706                 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL])) {
707                         if ($uid != 0) {
708                                 return 0;
709                         }
710
711                         // Get data from the gcontact table
712                         $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
713                         if (!DBM::is_result($gcontact)) {
714                                 return 0;
715                         }
716
717                         $data = array_merge($data, $gcontact);
718                 }
719
720                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
721                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
722                 }
723
724                 $url = $data["url"];
725                 if (!$contact_id) {
726                         dba::insert('contact', [
727                                 'uid'       => $uid,
728                                 'created'   => datetime_convert(),
729                                 'url'       => $data["url"],
730                                 'nurl'      => normalise_link($data["url"]),
731                                 'addr'      => $data["addr"],
732                                 'alias'     => $data["alias"],
733                                 'notify'    => $data["notify"],
734                                 'poll'      => $data["poll"],
735                                 'name'      => $data["name"],
736                                 'nick'      => $data["nick"],
737                                 'photo'     => $data["photo"],
738                                 'keywords'  => $data["keywords"],
739                                 'location'  => $data["location"],
740                                 'about'     => $data["about"],
741                                 'network'   => $data["network"],
742                                 'pubkey'    => $data["pubkey"],
743                                 'rel'       => CONTACT_IS_SHARING,
744                                 'priority'  => $data["priority"],
745                                 'batch'     => $data["batch"],
746                                 'request'   => $data["request"],
747                                 'confirm'   => $data["confirm"],
748                                 'poco'      => $data["poco"],
749                                 'name-date' => datetime_convert(),
750                                 'uri-date'  => datetime_convert(),
751                                 'avatar-date' => datetime_convert(),
752                                 'writable'  => 1,
753                                 'blocked'   => 0,
754                                 'readonly'  => 0,
755                                 'pending'   => 0]
756                         );
757
758                         $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
759                         $contacts = dba::inArray($s);
760                         if (!DBM::is_result($contacts)) {
761                                 return 0;
762                         }
763
764                         $contact_id = $contacts[0]["id"];
765
766                         // Update the newly created contact from data in the gcontact table
767                         $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
768                         if (DBM::is_result($gcontact)) {
769                                 // Only use the information when the probing hadn't fetched these values
770                                 if ($data['keywords'] != '') {
771                                         unset($gcontact['keywords']);
772                                 }
773                                 if ($data['location'] != '') {
774                                         unset($gcontact['location']);
775                                 }
776                                 if ($data['about'] != '') {
777                                         unset($gcontact['about']);
778                                 }
779                                 dba::update('contact', $gcontact, ['id' => $contact_id]);
780                         }
781
782                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
783                                 dba::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
784                                         normalise_link($data["url"]), $contact_id]);
785                         }
786                 }
787
788                 self::updateAvatar($data["photo"], $uid, $contact_id);
789
790                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
791                 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
792
793                 // This condition should always be true
794                 if (!DBM::is_result($contact)) {
795                         return $contact_id;
796                 }
797
798                 $updated = ['addr' => $data['addr'],
799                         'alias' => $data['alias'],
800                         'url' => $data['url'],
801                         'nurl' => normalise_link($data['url']),
802                         'name' => $data['name'],
803                         'nick' => $data['nick']];
804
805                 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
806                 if (!empty($contact['pubkey'])) {
807                         unset($contact['pubkey']);
808                 } else {
809                         $updated['pubkey'] = $data['pubkey'];
810                 }
811
812                 if ($data['keywords'] != '') {
813                         $updated['keywords'] = $data['keywords'];
814                 }
815                 if ($data['location'] != '') {
816                         $updated['location'] = $data['location'];
817                 }
818                 if ($data['about'] != '') {
819                         $updated['about'] = $data['about'];
820                 }
821
822                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
823                         $updated['uri-date'] = datetime_convert();
824                 }
825                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
826                         $updated['name-date'] = datetime_convert();
827                 }
828
829                 $updated['avatar-date'] = datetime_convert();
830
831                 dba::update('contact', $updated, ['id' => $contact_id], $contact);
832
833                 return $contact_id;
834         }
835
836         /**
837          * @brief Checks if the contact is blocked
838          *
839          * @param int $cid contact id
840          *
841          * @return boolean Is the contact blocked?
842          */
843         public static function isBlocked($cid)
844         {
845                 if ($cid == 0) {
846                         return false;
847                 }
848
849                 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
850                 if (!DBM::is_result($blocked)) {
851                         return false;
852                 }
853                 return (bool) $blocked['blocked'];
854         }
855
856         /**
857          * @brief Checks if the contact is hidden
858          *
859          * @param int $cid contact id
860          *
861          * @return boolean Is the contact hidden?
862          */
863         public static function isHidden($cid)
864         {
865                 if ($cid == 0) {
866                         return false;
867                 }
868
869                 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
870                 if (!DBM::is_result($hidden)) {
871                         return false;
872                 }
873                 return (bool) $hidden['hidden'];
874         }
875
876         /**
877          * @brief Returns posts from a given contact url
878          *
879          * @param string $contact_url Contact URL
880          *
881          * @return string posts in HTML
882          */
883         public static function getPostsFromUrl($contact_url)
884         {
885                 $a = self::getApp();
886
887                 require_once 'include/conversation.php';
888
889                 // There are no posts with "uid = 0" with connector networks
890                 // This speeds up the query a lot
891                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
892                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
893                         dbesc(normalise_link($contact_url))
894                 );
895
896                 if (!DBM::is_result($r)) {
897                         return '';
898                 }
899
900                 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
901                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
902                 } else {
903                         $sql = "`item`.`uid` = %d";
904                 }
905
906                 $author_id = intval($r[0]["author-id"]);
907
908                 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
909
910                 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
911                         " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
912                         intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
913                         intval($a->pager['start']), intval($a->pager['itemspage'])
914                 );
915
916                 $o = conversation($a, $r, 'contact-posts', false);
917
918                 $o .= alt_pager($a, count($r));
919
920                 return $o;
921         }
922
923         /**
924          * @brief Returns the account type name
925          *
926          * The function can be called with either the user or the contact array
927          *
928          * @param array $contact contact or user array
929          * @return string
930          */
931         public static function getAccountType(array $contact)
932         {
933                 // There are several fields that indicate that the contact or user is a forum
934                 // "page-flags" is a field in the user table,
935                 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
936                 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
937                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
938                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
939                         || (isset($contact['forum']) && intval($contact['forum']))
940                         || (isset($contact['prv']) && intval($contact['prv']))
941                         || (isset($contact['community']) && intval($contact['community']))
942                 ) {
943                         $type = ACCOUNT_TYPE_COMMUNITY;
944                 } else {
945                         $type = ACCOUNT_TYPE_PERSON;
946                 }
947
948                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
949                 if (isset($contact["contact-type"])) {
950                         $type = $contact["contact-type"];
951                 }
952
953                 if (isset($contact["account-type"])) {
954                         $type = $contact["account-type"];
955                 }
956
957                 switch ($type) {
958                         case ACCOUNT_TYPE_ORGANISATION:
959                                 $account_type = t("Organisation");
960                                 break;
961                         case ACCOUNT_TYPE_NEWS:
962                                 $account_type = t('News');
963                                 break;
964                         case ACCOUNT_TYPE_COMMUNITY:
965                                 $account_type = t("Forum");
966                                 break;
967                         default:
968                                 $account_type = "";
969                                 break;
970                 }
971
972                 return $account_type;
973         }
974
975         /**
976          * @brief Blocks a contact
977          *
978          * @param int $uid
979          * @return bool
980          */
981         public static function block($uid)
982         {
983                 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
984
985                 return $return;
986         }
987
988         /**
989          * @brief Unblocks a contact
990          *
991          * @param int $uid
992          * @return bool
993          */
994         public static function unblock($uid)
995         {
996                 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
997
998                 return $return;
999         }
1000
1001         /**
1002          * @brief Updates the avatar links in a contact only if needed
1003          *
1004          * @param string $avatar Link to avatar picture
1005          * @param int    $uid    User id of contact owner
1006          * @param int    $cid    Contact id
1007          * @param bool   $force  force picture update
1008          *
1009          * @return array Returns array of the different avatar sizes
1010          */
1011         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1012         {
1013                 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1014                 if (!DBM::is_result($contact)) {
1015                         return false;
1016                 } else {
1017                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1018                 }
1019
1020                 if (($contact["avatar"] != $avatar) || $force) {
1021                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1022
1023                         if ($photos) {
1024                                 dba::update(
1025                                         'contact',
1026                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()],
1027                                         ['id' => $cid]
1028                                 );
1029
1030                                 // Update the public contact (contact id = 0)
1031                                 if ($uid != 0) {
1032                                         $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl']]);
1033                                         if (DBM::is_result($pcontact)) {
1034                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1035                                         }
1036                                 }
1037
1038                                 return $photos;
1039                         }
1040                 }
1041
1042                 return $data;
1043         }
1044
1045         /**
1046          * @param integer $id contact id
1047          * @return boolean
1048          */
1049         public static function updateFromProbe($id)
1050         {
1051                 /*
1052                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1053                   This will reliably kill your communication with Friendica contacts.
1054                  */
1055
1056                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1057                 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1058                 if (!DBM::is_result($contact)) {
1059                         return false;
1060                 }
1061
1062                 $ret = Probe::uri($contact["url"]);
1063
1064                 // If Probe::uri fails the network code will be different
1065                 if ($ret["network"] != $contact["network"]) {
1066                         return false;
1067                 }
1068
1069                 $update = false;
1070
1071                 // make sure to not overwrite existing values with blank entries
1072                 foreach ($ret as $key => $val) {
1073                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1074                                 $ret[$key] = $contact[$key];
1075                         }
1076
1077                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1078                                 $update = true;
1079                         }
1080                 }
1081
1082                 if (!$update) {
1083                         return true;
1084                 }
1085
1086                 dba::update(
1087                         'contact', [
1088                                 'url'    => $ret['url'],
1089                                 'nurl'   => normalise_link($ret['url']),
1090                                 'addr'   => $ret['addr'],
1091                                 'alias'  => $ret['alias'],
1092                                 'batch'  => $ret['batch'],
1093                                 'notify' => $ret['notify'],
1094                                 'poll'   => $ret['poll'],
1095                                 'poco'   => $ret['poco']
1096                         ],
1097                         ['id' => $id]
1098                 );
1099
1100                 // Update the corresponding gcontact entry
1101                 PortableContact::lastUpdated($ret["url"]);
1102
1103                 return true;
1104         }
1105
1106         /**
1107          * Takes a $uid and a url/handle and adds a new contact
1108          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1109          * dfrn_request page.
1110          *
1111          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1112          *
1113          * Returns an array
1114          * $return['success'] boolean true if successful
1115          * $return['message'] error text if success is false.
1116          *
1117          * @brief Takes a $uid and a url/handle and adds a new contact
1118          * @param int    $uid
1119          * @param string $url
1120          * @param bool   $interactive
1121          * @param string $network
1122          * @return boolean|string
1123          */
1124         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1125         {
1126                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1127
1128                 $a = get_app();
1129
1130                 // remove ajax junk, e.g. Twitter
1131                 $url = str_replace('/#!/', '/', $url);
1132
1133                 if (!allowed_url($url)) {
1134                         $result['message'] = t('Disallowed profile URL.');
1135                         return $result;
1136                 }
1137
1138                 if (blocked_url($url)) {
1139                         $result['message'] = t('Blocked domain');
1140                         return $result;
1141                 }
1142
1143                 if (!$url) {
1144                         $result['message'] = t('Connect URL missing.');
1145                         return $result;
1146                 }
1147
1148                 $arr = ['url' => $url, 'contact' => []];
1149
1150                 Addon::callHooks('follow', $arr);
1151
1152                 if (x($arr['contact'], 'name')) {
1153                         $ret = $arr['contact'];
1154                 } else {
1155                         $ret = Probe::uri($url, $network, $uid, false);
1156                 }
1157
1158                 if (($network != '') && ($ret['network'] != $network)) {
1159                         logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1160                         return result;
1161                 }
1162
1163                 if ($ret['network'] === NETWORK_DFRN) {
1164                         if ($interactive) {
1165                                 if (strlen($a->path)) {
1166                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1167                                 } else {
1168                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1169                                 }
1170
1171                                 goaway($ret['request'] . "&addr=$myaddr");
1172
1173                                 // NOTREACHED
1174                         }
1175                 } elseif (Config::get('system', 'dfrn_only')) {
1176                         $result['message'] = t('This site is not configured to allow communications with other networks.') . EOL;
1177                         $result['message'] != t('No compatible communication protocols or feeds were discovered.') . EOL;
1178                         return $result;
1179                 }
1180
1181                 // This extra param just confuses things, remove it
1182                 if ($ret['network'] === NETWORK_DIASPORA) {
1183                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1184                 }
1185
1186                 // do we have enough information?
1187
1188                 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1189                         $result['message'] .= t('The profile address specified does not provide adequate information.') . EOL;
1190                         if (!x($ret, 'poll')) {
1191                                 $result['message'] .= t('No compatible communication protocols or feeds were discovered.') . EOL;
1192                         }
1193                         if (!x($ret, 'name')) {
1194                                 $result['message'] .= t('An author or name was not found.') . EOL;
1195                         }
1196                         if (!x($ret, 'url')) {
1197                                 $result['message'] .= t('No browser URL could be matched to this address.') . EOL;
1198                         }
1199                         if (strpos($url, '@') !== false) {
1200                                 $result['message'] .= t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1201                                 $result['message'] .= t('Use mailto: in front of address to force email check.') . EOL;
1202                         }
1203                         return $result;
1204                 }
1205
1206                 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1207                         $result['message'] .= t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1208                         $ret['notify'] = '';
1209                 }
1210
1211                 if (!$ret['notify']) {
1212                         $result['message'] .= t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1213                 }
1214
1215                 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1216
1217                 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1218
1219                 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1220
1221                 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1222                         $writeable = 1;
1223                 }
1224
1225                 // check if we already have a contact
1226                 // the poll url is more reliable than the profile url, as we may have
1227                 // indirect links or webfinger links
1228
1229                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1230                         intval($uid),
1231                         dbesc($ret['poll']),
1232                         dbesc(normalise_link($ret['poll'])),
1233                         dbesc($ret['network'])
1234                 );
1235
1236                 if (!DBM::is_result($r)) {
1237                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1238                                 intval($uid),
1239                                 dbesc(normalise_link($url)),
1240                                 dbesc($ret['network'])
1241                         );
1242                 }
1243
1244                 if (DBM::is_result($r)) {
1245                         // update contact
1246                         $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1247
1248                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1249                         dba::update('contact', $fields, ['id' => $r[0]['id']]);
1250                 } else {
1251                         $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1252
1253                         // create contact record
1254                         dba::insert('contact', [
1255                                 'uid'     => $uid,
1256                                 'created' => datetime_convert(),
1257                                 'url'     => $ret['url'],
1258                                 'nurl'    => normalise_link($ret['url']),
1259                                 'addr'    => $ret['addr'],
1260                                 'alias'   => $ret['alias'],
1261                                 'batch'   => $ret['batch'],
1262                                 'notify'  => $ret['notify'],
1263                                 'poll'    => $ret['poll'],
1264                                 'poco'    => $ret['poco'],
1265                                 'name'    => $ret['name'],
1266                                 'nick'    => $ret['nick'],
1267                                 'network' => $ret['network'],
1268                                 'pubkey'  => $ret['pubkey'],
1269                                 'rel'     => $new_relation,
1270                                 'priority'=> $ret['priority'],
1271                                 'writable'=> $writeable,
1272                                 'hidden'  => $hidden,
1273                                 'blocked' => 0,
1274                                 'readonly'=> 0,
1275                                 'pending' => 0,
1276                                 'subhub'  => $subhub
1277                         ]);
1278                 }
1279
1280                 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1281                 if (!DBM::is_result($contact)) {
1282                         $result['message'] .= t('Unable to retrieve contact information.') . EOL;
1283                         return $result;
1284                 }
1285
1286                 $contact_id = $contact['id'];
1287                 $result['cid'] = $contact_id;
1288
1289                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1290
1291                 // Update the avatar
1292                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1293
1294                 // pull feed and consume it, which should subscribe to the hub.
1295
1296                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1297
1298                 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1299                         WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1300                         intval($uid)
1301                 );
1302
1303                 if (DBM::is_result($r)) {
1304                         if (($contact['network'] == NETWORK_OSTATUS) && (strlen($contact['notify']))) {
1305                                 // create a follow slap
1306                                 $item = [];
1307                                 $item['verb'] = ACTIVITY_FOLLOW;
1308                                 $item['follow'] = $contact["url"];
1309                                 $slap = OStatus::salmon($item, $r[0]);
1310                                 Salmon::slapper($r[0], $contact['notify'], $slap);
1311                         }
1312
1313                         if ($contact['network'] == NETWORK_DIASPORA) {
1314                                 $ret = Diaspora::sendShare($a->user, $contact);
1315                                 logger('share returns: ' . $ret);
1316                         }
1317                 }
1318
1319                 $result['success'] = true;
1320                 return $result;
1321         }
1322 }