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