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