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