]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Improve dba::selectFirst calls
[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                 $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', array('archive' => true, 'network' => 'none', 'writable' => false), array('id' => $id));
156                         return;
157                 }
158
159                 dba::delete('contact', array('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 = array();
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', array('term-date' => datetime_convert()), array('id' => $contact['id']));
212
213                         if ($contact['url'] != '') {
214                                 dba::update('contact', array('term-date' => datetime_convert()), array('`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', array('archive' => 1), array('id' => $contact['id']));
231
232                                 if ($contact['url'] != '') {
233                                         dba::update('contact', array('archive' => 1), array('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 = array('`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 = array('term-date' => NULL_DATE, 'archive' => false);
259                 dba::update('contact', $fields, array('id' => $contact['id']));
260
261                 if ($contact['url'] != '') {
262                         dba::update('contact', $fields, array('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 = array();
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"], array(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 = array();
423
424                 if ($addr == '') {
425                         return array();
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", dbesc($addr), intval($uid));
436
437                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
438                 if (!DBM::is_result($r))
439                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
440                         `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
441                         FROM `contact` WHERE `addr` = '%s' AND `uid` = 0", dbesc($addr));
442
443                 // Fetch the data from the gcontact table
444                 if (!DBM::is_result($r))
445                         $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`,
446                         `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
447                         FROM `gcontact` WHERE `addr` = '%s'", dbesc($addr));
448
449                 if (!DBM::is_result($r)) {
450                         $data = Probe::uri($addr);
451
452                         $profile = self::getDetailsByURL($data['url'], $uid);
453                 } else {
454                         $profile = $r[0];
455                 }
456
457                 return $profile;
458         }
459
460         /**
461          * @brief Returns the data array for the photo menu of a given contact
462          *
463          * @param array $contact contact
464          * @param int   $uid     optional, default 0
465          * @return array
466          */
467         public static function photoMenu(array $contact, $uid = 0)
468         {
469                 // @todo Unused, to be removed
470                 $a = get_app();
471
472                 $contact_url = '';
473                 $pm_url = '';
474                 $status_link = '';
475                 $photos_link = '';
476                 $posts_link = '';
477                 $contact_drop_link = '';
478                 $poke_link = '';
479
480                 if ($uid == 0) {
481                         $uid = local_user();
482                 }
483
484                 if ($contact['uid'] != $uid) {
485                         if ($uid == 0) {
486                                 $profile_link = zrl($contact['url']);
487                                 $menu = array('profile' => array(t('View Profile'), $profile_link, true));
488
489                                 return $menu;
490                         }
491
492                         // Look for our own contact if the uid doesn't match and isn't public
493                         $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
494                         if (DBM::is_result($contact_own)) {
495                                 return self::photoMenu($contact_own, $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                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
668                         $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
669                 }
670
671                 if (DBM::is_result($contact)) {
672                         $contact_id = $contact["id"];
673
674                         // Update the contact every 7 days
675                         $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
676
677                         // We force the update if the avatar is empty
678                         if (!x($contact, 'avatar')) {
679                                 $update_contact = true;
680                         }
681
682                         if (!$update_contact || $no_update) {
683                                 return $contact_id;
684                         }
685                 } elseif ($uid != 0) {
686                         // Non-existing user-specific contact, exiting
687                         return 0;
688                 }
689
690                 $data = Probe::uri($url, "", $uid);
691
692                 // Last try in gcontact for unsupported networks
693                 if (!in_array($data["network"], array(NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL))) {
694                         if ($uid != 0) {
695                                 return 0;
696                         }
697
698                         // Get data from the gcontact table
699                         $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
700                         if (!DBM::is_result($gcontact)) {
701                                 return 0;
702                         }
703
704                         $data = array_merge($data, $gcontact);
705                 }
706
707                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
708                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
709                 }
710
711                 $url = $data["url"];
712                 if (!$contact_id) {
713                         dba::insert(
714                                 'contact', array('uid' => $uid, 'created' => datetime_convert(), 'url' => $data["url"],
715                                 'nurl' => normalise_link($data["url"]), 'addr' => $data["addr"],
716                                 'alias' => $data["alias"], 'notify' => $data["notify"], 'poll' => $data["poll"],
717                                 'name' => $data["name"], 'nick' => $data["nick"], 'photo' => $data["photo"],
718                                 'keywords' => $data["keywords"], 'location' => $data["location"], 'about' => $data["about"],
719                                 'network' => $data["network"], 'pubkey' => $data["pubkey"],
720                                 'rel' => CONTACT_IS_SHARING, 'priority' => $data["priority"],
721                                 'batch' => $data["batch"], 'request' => $data["request"],
722                                 'confirm' => $data["confirm"], 'poco' => $data["poco"],
723                                 'name-date' => datetime_convert(), 'uri-date' => datetime_convert(),
724                                 'avatar-date' => datetime_convert(), 'writable' => 1, 'blocked' => 0,
725                                 'readonly' => 0, 'pending' => 0)
726                         );
727
728                         $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
729                         $contacts = dba::inArray($s);
730                         if (!DBM::is_result($contacts)) {
731                                 return 0;
732                         }
733
734                         $contact_id = $contacts[0]["id"];
735
736                         // Update the newly created contact from data in the gcontact table
737                         $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
738                         if (DBM::is_result($gcontact)) {
739                                 // Only use the information when the probing hadn't fetched these values
740                                 if ($data['keywords'] != '') {
741                                         unset($gcontact['keywords']);
742                                 }
743                                 if ($data['location'] != '') {
744                                         unset($gcontact['location']);
745                                 }
746                                 if ($data['about'] != '') {
747                                         unset($gcontact['about']);
748                                 }
749                                 dba::update('contact', $gcontact, array('id' => $contact_id));
750                         }
751
752                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
753                                 dba::delete('contact', array("`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
754                                         normalise_link($data["url"]), $contact_id));
755                         }
756                 }
757
758                 self::updateAvatar($data["photo"], $uid, $contact_id);
759
760                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
761                 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
762
763                 // This condition should always be true
764                 if (!DBM::is_result($contact)) {
765                         return $contact_id;
766                 }
767
768                 $updated = array('addr' => $data['addr'],
769                         'alias' => $data['alias'],
770                         'url' => $data['url'],
771                         'nurl' => normalise_link($data['url']),
772                         'name' => $data['name'],
773                         'nick' => $data['nick']);
774
775                 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
776                 if (!empty($contact['pubkey'])) {
777                         unset($contact['pubkey']);
778                 } else {
779                         $updated['pubkey'] = $data['pubkey'];
780                 }
781
782                 if ($data['keywords'] != '') {
783                         $updated['keywords'] = $data['keywords'];
784                 }
785                 if ($data['location'] != '') {
786                         $updated['location'] = $data['location'];
787                 }
788                 if ($data['about'] != '') {
789                         $updated['about'] = $data['about'];
790                 }
791
792                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
793                         $updated['uri-date'] = datetime_convert();
794                 }
795                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
796                         $updated['name-date'] = datetime_convert();
797                 }
798
799                 $updated['avatar-date'] = datetime_convert();
800
801                 dba::update('contact', $updated, array('id' => $contact_id), $contact);
802
803                 return $contact_id;
804         }
805
806         /**
807          * @brief Checks if the contact is blocked
808          *
809          * @param int $cid contact id
810          *
811          * @return boolean Is the contact blocked?
812          */
813         public static function isBlocked($cid)
814         {
815                 if ($cid == 0) {
816                         return false;
817                 }
818
819                 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
820                 if (!DBM::is_result($blocked)) {
821                         return false;
822                 }
823                 return (bool) $blocked['blocked'];
824         }
825
826         /**
827          * @brief Checks if the contact is hidden
828          *
829          * @param int $cid contact id
830          *
831          * @return boolean Is the contact hidden?
832          */
833         public static function isHidden($cid)
834         {
835                 if ($cid == 0) {
836                         return false;
837                 }
838
839                 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
840                 if (!DBM::is_result($hidden)) {
841                         return false;
842                 }
843                 return (bool) $hidden['hidden'];
844         }
845
846         /**
847          * @brief Returns posts from a given contact url
848          *
849          * @param string $contact_url Contact URL
850          *
851          * @return string posts in HTML
852          */
853         public static function getPostsFromUrl($contact_url)
854         {
855                 $a = self::getApp();
856
857                 require_once 'include/conversation.php';
858
859                 // There are no posts with "uid = 0" with connector networks
860                 // This speeds up the query a lot
861                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
862                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0", dbesc(normalise_link($contact_url)));
863
864                 if (!DBM::is_result($r)) {
865                         return '';
866                 }
867
868                 if (in_array($r[0]["network"], array(NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""))) {
869                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
870                 } else {
871                         $sql = "`item`.`uid` = %d";
872                 }
873
874                 $author_id = intval($r[0]["author-id"]);
875
876                 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
877
878                 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
879                         " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
880                         intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
881                         intval($a->pager['start']), intval($a->pager['itemspage'])
882                 );
883
884
885                 $o = conversation($a, $r, 'contact-posts', false);
886
887                 $o .= alt_pager($a, count($r));
888
889                 return $o;
890         }
891
892         /**
893          * @brief Returns the account type name
894          *
895          * The function can be called with either the user or the contact array
896          *
897          * @param array $contact contact or user array
898          * @return string
899          */
900         public static function getAccountType(array $contact)
901         {
902                 // There are several fields that indicate that the contact or user is a forum
903                 // "page-flags" is a field in the user table,
904                 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
905                 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
906                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
907                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
908                         || (isset($contact['forum']) && intval($contact['forum']))
909                         || (isset($contact['prv']) && intval($contact['prv']))
910                         || (isset($contact['community']) && intval($contact['community']))
911                 ) {
912                         $type = ACCOUNT_TYPE_COMMUNITY;
913                 } else {
914                         $type = ACCOUNT_TYPE_PERSON;
915                 }
916
917                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
918                 if (isset($contact["contact-type"])) {
919                         $type = $contact["contact-type"];
920                 }
921                 if (isset($contact["account-type"])) {
922                         $type = $contact["account-type"];
923                 }
924
925                 switch ($type) {
926                         case ACCOUNT_TYPE_ORGANISATION:
927                                 $account_type = t("Organisation");
928                                 break;
929                         case ACCOUNT_TYPE_NEWS:
930                                 $account_type = t('News');
931                                 break;
932                         case ACCOUNT_TYPE_COMMUNITY:
933                                 $account_type = t("Forum");
934                                 break;
935                         default:
936                                 $account_type = "";
937                                 break;
938                 }
939
940                 return $account_type;
941         }
942
943         /**
944          * @brief Blocks a contact
945          *
946          * @param int $uid
947          * @return bool
948          */
949         public static function block($uid)
950         {
951                 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
952
953                 return $return;
954         }
955
956         /**
957          * @brief Unblocks a contact
958          *
959          * @param int $uid
960          * @return bool
961          */
962         public static function unblock($uid)
963         {
964                 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
965
966                 return $return;
967   }
968
969   /**
970    * @brief Updates the avatar links in a contact only if needed
971          *
972          * @param string $avatar Link to avatar picture
973          * @param int    $uid    User id of contact owner
974          * @param int    $cid    Contact id
975          * @param bool   $force  force picture update
976          *
977          * @return array Returns array of the different avatar sizes
978          */
979         public static function updateAvatar($avatar, $uid, $cid, $force = false)
980         {
981                 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
982                 if (!DBM::is_result($contact)) {
983                         return false;
984                 } else {
985                         $data = array($contact["photo"], $contact["thumb"], $contact["micro"]);
986                 }
987
988                 if (($contact["avatar"] != $avatar) || $force) {
989                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
990
991                         if ($photos) {
992                                 dba::update(
993                                         'contact',
994                                         array('avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()),
995                                         array('id' => $cid)
996                                 );
997
998                                 // Update the public contact (contact id = 0)
999                                 if ($uid != 0) {
1000                                         $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl']]);
1001                                         if (DBM::is_result($pcontact)) {
1002                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1003                                         }
1004                                 }
1005
1006                                 return $photos;
1007                         }
1008                 }
1009
1010                 return $data;
1011         }
1012
1013         /**
1014          * @param integer $id contact id
1015          * @return boolean
1016          */
1017         public static function updateFromProbe($id)
1018         {
1019                 /*
1020                 Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1021                 This will reliably kill your communication with Friendica contacts.
1022                 */
1023
1024                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1025                 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1026                 if (!DBM::is_result($contact)) {
1027                         return false;
1028                 }
1029
1030                 $ret = Probe::uri($contact["url"]);
1031
1032                 // If Probe::uri fails the network code will be different
1033                 if ($ret["network"] != $contact["network"]) {
1034                         return false;
1035                 }
1036
1037                 $update = false;
1038
1039                 // make sure to not overwrite existing values with blank entries
1040                 foreach ($ret as $key => $val) {
1041                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1042                                 $ret[$key] = $contact[$key];
1043                         }
1044
1045                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1046                                 $update = true;
1047                         }
1048                 }
1049
1050                 if (!$update) {
1051                         return true;
1052                 }
1053
1054                 dba::update(
1055                         'contact',
1056                         [
1057                                 'url' => $ret['url'],
1058                                 'nurl' => normalise_link($ret['url']),
1059                                 'addr' => $ret['addr'],
1060                                 'alias' => $ret['alias'],
1061                                 'batch' => $ret['batch'],
1062                                 'notify' => $ret['notify'],
1063                                 'poll' => $ret['poll'],
1064                                 'poco' => $ret['poco']
1065                         ],
1066                         ['id' => $id]
1067                 );
1068
1069                 // Update the corresponding gcontact entry
1070                 PortableContact::lastUpdated($ret["url"]);
1071
1072                 return true;
1073         }
1074
1075         /**
1076          * Takes a $uid and a url/handle and adds a new contact
1077          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1078          * dfrn_request page.
1079          *
1080          * Otherwise this can be used to bulk add statusnet contacts, twitter contacts, etc.
1081          *
1082          * Returns an array
1083          * $return['success'] boolean true if successful
1084          * $return['message'] error text if success is false.
1085          *
1086          * @brief Takes a $uid and a url/handle and adds a new contact
1087          * @param int    $uid
1088          * @param string $url
1089          * @param bool   $interactive
1090          * @param string $network
1091          * @return boolean|string
1092          */
1093         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1094         {
1095                 $result = array('cid' => -1, 'success' => false, 'message' => '');
1096
1097                 $a = get_app();
1098
1099                 // remove ajax junk, e.g. Twitter
1100                 $url = str_replace('/#!/', '/', $url);
1101
1102                 if (!allowed_url($url)) {
1103                         $result['message'] = t('Disallowed profile URL.');
1104                         return $result;
1105                 }
1106
1107                 if (blocked_url($url)) {
1108                         $result['message'] = t('Blocked domain');
1109                         return $result;
1110                 }
1111
1112                 if (!$url) {
1113                         $result['message'] = t('Connect URL missing.');
1114                         return $result;
1115                 }
1116
1117                 $arr = array('url' => $url, 'contact' => array());
1118
1119                 call_hooks('follow', $arr);
1120
1121                 if (x($arr['contact'], 'name')) {
1122                         $ret = $arr['contact'];
1123                 } else {
1124                         $ret = Probe::uri($url, $network, $uid, false);
1125                 }
1126
1127                 if (($network != '') && ($ret['network'] != $network)) {
1128                         logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1129                         return result;
1130                 }
1131
1132                 if ($ret['network'] === NETWORK_DFRN) {
1133                         if ($interactive) {
1134                                 if (strlen($a->path)) {
1135                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1136                                 } else {
1137                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1138                                 }
1139
1140                                 goaway($ret['request'] . "&addr=$myaddr");
1141
1142                                 // NOTREACHED
1143                         }
1144                 } elseif (Config::get('system', 'dfrn_only')) {
1145                         $result['message'] = t('This site is not configured to allow communications with other networks.') . EOL;
1146                         $result['message'] != t('No compatible communication protocols or feeds were discovered.') . EOL;
1147                         return $result;
1148                 }
1149
1150                 // This extra param just confuses things, remove it
1151                 if ($ret['network'] === NETWORK_DIASPORA) {
1152                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1153                 }
1154
1155                 // do we have enough information?
1156
1157                 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1158                         $result['message'] .= t('The profile address specified does not provide adequate information.') . EOL;
1159                         if (!x($ret, 'poll')) {
1160                                 $result['message'] .= t('No compatible communication protocols or feeds were discovered.') . EOL;
1161                         }
1162                         if (!x($ret, 'name')) {
1163                                 $result['message'] .= t('An author or name was not found.') . EOL;
1164                         }
1165                         if (!x($ret, 'url')) {
1166                                 $result['message'] .= t('No browser URL could be matched to this address.') . EOL;
1167                         }
1168                         if (strpos($url, '@') !== false) {
1169                                 $result['message'] .= t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1170                                 $result['message'] .= t('Use mailto: in front of address to force email check.') . EOL;
1171                         }
1172                         return $result;
1173                 }
1174
1175                 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1176                         $result['message'] .= t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1177                         $ret['notify'] = '';
1178                 }
1179
1180                 if (!$ret['notify']) {
1181                         $result['message'] .= t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1182                 }
1183
1184                 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1185
1186                 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1187
1188                 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1189
1190                 if (in_array($ret['network'], array(NETWORK_MAIL, NETWORK_DIASPORA))) {
1191                         $writeable = 1;
1192                 }
1193
1194                 // check if we already have a contact
1195                 // the poll url is more reliable than the profile url, as we may have
1196                 // indirect links or webfinger links
1197
1198                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1199                         intval($uid),
1200                         dbesc($ret['poll']),
1201                         dbesc(normalise_link($ret['poll'])),
1202                         dbesc($ret['network'])
1203                 );
1204
1205                 if (!DBM::is_result($r)) {
1206                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1207                                 intval($uid), dbesc(normalise_link($url)), dbesc($ret['network'])
1208                         );
1209                 }
1210
1211                 if (DBM::is_result($r)) {
1212                         // update contact
1213                         $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1214
1215                         $fields = array('rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false);
1216                         dba::update('contact', $fields, array('id' => $r[0]['id']));
1217                 } else {
1218                         $new_relation = ((in_array($ret['network'], array(NETWORK_MAIL))) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1219
1220                         // create contact record
1221                         dba::insert(
1222                                 'contact',
1223                                 [
1224                                         'uid' => $uid,
1225                                         'created' => datetime_convert(),
1226                                         'url' => $ret['url'],
1227                                         'nurl' => normalise_link($ret['url']),
1228                                         'addr' => $ret['addr'],
1229                                         'alias' => $ret['alias'],
1230                                         'batch' => $ret['batch'],
1231                                         'notify' => $ret['notify'],
1232                                         'poll' => $ret['poll'],
1233                                         'poco' => $ret['poco'],
1234                                         'name' => $ret['name'],
1235                                         'nick' => $ret['nick'],
1236                                         'network' => $ret['network'],
1237                                         'pubkey' => $ret['pubkey'],
1238                                         'rel' => $new_relation,
1239                                         'priority' => $ret['priority'],
1240                                         'writable' => $writeable,
1241                                         'hidden' => $hidden,
1242                                         'blocked' => 0,
1243                                         'readonly' => 0,
1244                                         'pending' => 0,
1245                                         'subhub' => $subhub
1246                                 ]
1247                         );
1248                 }
1249
1250                 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1251                 if (!DBM::is_result($contact)) {
1252                         $result['message'] .= t('Unable to retrieve contact information.') . EOL;
1253                         return $result;
1254                 }
1255
1256                 $contact_id = $contact['id'];
1257                 $result['cid'] = $contact_id;
1258
1259                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1260
1261                 // Update the avatar
1262                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1263
1264                 // pull feed and consume it, which should subscribe to the hub.
1265
1266                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1267
1268                 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1269                                 WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1270                                 intval($uid)
1271                 );
1272
1273                 if (DBM::is_result($r)) {
1274                         if (($contact['network'] == NETWORK_OSTATUS) && (strlen($contact['notify']))) {
1275                                 // create a follow slap
1276                                 $item = array();
1277                                 $item['verb'] = ACTIVITY_FOLLOW;
1278                                 $item['follow'] = $contact["url"];
1279                                 $slap = OStatus::salmon($item, $r[0]);
1280                                 Salmon::slapper($r[0], $contact['notify'], $slap);
1281                         }
1282
1283                         if ($contact['network'] == NETWORK_DIASPORA) {
1284                                 $ret = Diaspora::sendShare($a->user, $contact);
1285                                 logger('share returns: ' . $ret);
1286                         }
1287                 }
1288
1289                 $result['success'] = true;
1290                 return $result;
1291         }
1292 }