]> git.mxchange.org Git - friendica.git/blob - src/Model/Contact.php
Review update
[friendica.git] / src / Model / Contact.php
1 <?php
2 /**
3  * @file src/Model/Contact.php
4  */
5 namespace Friendica\Model;
6
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\L10n;
11 use Friendica\Core\PConfig;
12 use Friendica\Core\System;
13 use Friendica\Core\Worker;
14 use Friendica\Database\DBM;
15 use Friendica\Network\Probe;
16 use Friendica\Model\Photo;
17 use Friendica\Model\Profile;
18 use Friendica\Protocol\Diaspora;
19 use Friendica\Protocol\DFRN;
20 use Friendica\Protocol\OStatus;
21 use Friendica\Protocol\PortableContact;
22 use Friendica\Protocol\Salmon;
23 use Friendica\Util\Network;
24 use dba;
25
26 require_once 'boot.php';
27 require_once 'include/dba.php';
28 require_once 'include/text.php';
29
30 /**
31  * @brief functions for interacting with a contact
32  */
33 class Contact extends BaseObject
34 {
35         /**
36          * @brief Returns a list of contacts belonging in a group
37          *
38          * @param int $gid
39          * @return array
40          */
41         public static function getByGroupId($gid)
42         {
43                 $return = [];
44                 if (intval($gid)) {
45                         $stmt = dba::p('SELECT `group_member`.`contact-id`, `contact`.*
46                                 FROM `contact`
47                                 INNER JOIN `group_member`
48                                         ON `contact`.`id` = `group_member`.`contact-id`
49                                 WHERE `gid` = ?
50                                 AND `contact`.`uid` = ?
51                                 AND NOT `contact`.`self`
52                                 AND NOT `contact`.`blocked`
53                                 AND NOT `contact`.`pending`
54                                 ORDER BY `contact`.`name` ASC',
55                                 $gid,
56                                 local_user()
57                         );
58                         if (DBM::is_result($stmt)) {
59                                 $return = dba::inArray($stmt);
60                         }
61                 }
62
63                 return $return;
64         }
65
66         /**
67          * @brief Returns the count of OStatus contacts in a group
68          *
69          * @param int $gid
70          * @return int
71          */
72         public static function getOStatusCountByGroupId($gid)
73         {
74                 $return = 0;
75                 if (intval($gid)) {
76                         $contacts = dba::fetch_first('SELECT COUNT(*) AS `count`
77                                 FROM `contact`
78                                 INNER JOIN `group_member`
79                                         ON `contact`.`id` = `group_member`.`contact-id`
80                                 WHERE `gid` = ?
81                                 AND `contact`.`uid` = ?
82                                 AND `contact`.`network` = ?
83                                 AND `contact`.`notify` != ""',
84                                 $gid,
85                                 local_user(),
86                                 NETWORK_OSTATUS
87                         );
88                         $return = $contacts['count'];
89                 }
90
91                 return $return;
92         }
93
94         /**
95          * Creates the self-contact for the provided user id
96          *
97          * @param int $uid
98          * @return bool Operation success
99          */
100         public static function createSelfFromUserId($uid)
101         {
102                 // Only create the entry if it doesn't exist yet
103                 if (dba::exists('contact', ['uid' => $uid, 'self' => true])) {
104                         return true;
105                 }
106
107                 $user = dba::selectFirst('user', ['uid', 'username', 'nickname'], ['uid' => $uid]);
108                 if (!DBM::is_result($user)) {
109                         return false;
110                 }
111
112                 $return = dba::insert('contact', [
113                         'uid'         => $user['uid'],
114                         'created'     => datetime_convert(),
115                         'self'        => 1,
116                         'name'        => $user['username'],
117                         'nick'        => $user['nickname'],
118                         'photo'       => System::baseUrl() . '/photo/profile/' . $user['uid'] . '.jpg',
119                         'thumb'       => System::baseUrl() . '/photo/avatar/'  . $user['uid'] . '.jpg',
120                         'micro'       => System::baseUrl() . '/photo/micro/'   . $user['uid'] . '.jpg',
121                         'blocked'     => 0,
122                         'pending'     => 0,
123                         'url'         => System::baseUrl() . '/profile/' . $user['nickname'],
124                         'nurl'        => normalise_link(System::baseUrl() . '/profile/' . $user['nickname']),
125                         'addr'        => $user['nickname'] . '@' . substr(System::baseUrl(), strpos(System::baseUrl(), '://') + 3),
126                         'request'     => System::baseUrl() . '/dfrn_request/' . $user['nickname'],
127                         'notify'      => System::baseUrl() . '/dfrn_notify/'  . $user['nickname'],
128                         'poll'        => System::baseUrl() . '/dfrn_poll/'    . $user['nickname'],
129                         'confirm'     => System::baseUrl() . '/dfrn_confirm/' . $user['nickname'],
130                         'poco'        => System::baseUrl() . '/poco/'         . $user['nickname'],
131                         'name-date'   => datetime_convert(),
132                         'uri-date'    => datetime_convert(),
133                         'avatar-date' => datetime_convert(),
134                         'closeness'   => 0
135                 ]);
136
137                 return $return;
138         }
139
140         /**
141          * @brief Marks a contact for removal
142          *
143          * @param int $id contact id
144          * @return null
145          */
146         public static function remove($id)
147         {
148                 // We want just to make sure that we don't delete our "self" contact
149                 $contact = dba::selectFirst('contact', ['uid'], ['id' => $id, 'self' => false]);
150                 if (!DBM::is_result($contact) || !intval($contact['uid'])) {
151                         return;
152                 }
153
154                 $archive = PConfig::get($contact['uid'], 'system', 'archive_removed_contacts');
155                 if ($archive) {
156                         dba::update('contact', ['archive' => true, 'network' => 'none', 'writable' => false], ['id' => $id]);
157                         return;
158                 }
159
160                 dba::delete('contact', ['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 = [];
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', ['term-date' => datetime_convert()], ['id' => $contact['id']]);
213
214                         if ($contact['url'] != '') {
215                                 dba::update('contact', ['term-date' => datetime_convert()], ['`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', ['archive' => 1], ['id' => $contact['id']]);
232
233                                 if ($contact['url'] != '') {
234                                         dba::update('contact', ['archive' => 1], ['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 = ['`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 = ['term-date' => NULL_DATE, 'archive' => false];
260                 dba::update('contact', $fields, ['id' => $contact['id']]);
261
262                 if ($contact['url'] != '') {
263                         dba::update('contact', $fields, ['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 = [];
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"], [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 = [];
424
425                 if ($addr == '') {
426                         return [];
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",
437                         dbesc($addr),
438                         intval($uid)
439                 );
440                 // Fetch the data from the contact table with "uid=0" (which is filled automatically)
441                 if (!DBM::is_result($r)) {
442                         $r = q("SELECT `id`, 0 AS `cid`, `id` AS `zid`, 0 AS `gid`, `uid`, `url`, `nurl`, `alias`, `network`, `name`, `nick`, `addr`, `location`, `about`, `xmpp`,
443                                 `keywords`, `gender`, `photo`, `thumb`, `micro`, `forum`, `prv`, (`forum` | `prv`) AS `community`, `contact-type`, `bd` AS `birthday`, 0 AS `self`
444                                 FROM `contact` WHERE `addr` = '%s' AND `uid` = 0",
445                                 dbesc($addr)
446                         );
447                 }
448
449                 // Fetch the data from the gcontact table
450                 if (!DBM::is_result($r)) {
451                         $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`,
452                                 `keywords`, `gender`, `photo`, `photo` AS `thumb`, `photo` AS `micro`, `community` AS `forum`, 0 AS `prv`, `community`, `contact-type`, `birthday`, 0 AS `self`
453                                 FROM `gcontact` WHERE `addr` = '%s'",
454                                 dbesc($addr)
455                         );
456                 }
457
458                 if (!DBM::is_result($r)) {
459                         $data = Probe::uri($addr);
460
461                         $profile = self::getDetailsByURL($data['url'], $uid);
462                 } else {
463                         $profile = $r[0];
464                 }
465
466                 return $profile;
467         }
468
469         /**
470          * @brief Returns the data array for the photo menu of a given contact
471          *
472          * @param array $contact contact
473          * @param int   $uid     optional, default 0
474          * @return array
475          */
476         public static function photoMenu(array $contact, $uid = 0)
477         {
478                 // @todo Unused, to be removed
479                 $a = get_app();
480
481                 $contact_url = '';
482                 $pm_url = '';
483                 $status_link = '';
484                 $photos_link = '';
485                 $posts_link = '';
486                 $contact_drop_link = '';
487                 $poke_link = '';
488
489                 if ($uid == 0) {
490                         $uid = local_user();
491                 }
492
493                 if ($contact['uid'] != $uid) {
494                         if ($uid == 0) {
495                                 $profile_link = Profile::zrl($contact['url']);
496                                 $menu = ['profile' => [L10n::t('View Profile'), $profile_link, true]];
497
498                                 return $menu;
499                         }
500
501                         // Look for our own contact if the uid doesn't match and isn't public
502                         $contact_own = dba::selectFirst('contact', [], ['nurl' => $contact['nurl'], 'network' => $contact['network'], 'uid' => $uid]);
503                         if (DBM::is_result($contact_own)) {
504                                 return self::photoMenu($contact_own, $uid);
505                         } else {
506                                 $profile_link = Profile::zrl($contact['url']);
507                                 $connlnk = 'follow/?url=' . $contact['url'];
508                                 $menu = [
509                                         'profile' => [L10n::t('View Profile'), $profile_link, true],
510                                         'follow' => [L10n::t('Connect/Follow'), $connlnk, true]
511                                 ];
512
513                                 return $menu;
514                         }
515                 }
516
517                 $sparkle = false;
518                 if ($contact['network'] === NETWORK_DFRN) {
519                         $sparkle = true;
520                         $profile_link = System::baseUrl() . '/redir/' . $contact['id'];
521                 } else {
522                         $profile_link = $contact['url'];
523                 }
524
525                 if ($profile_link === 'mailbox') {
526                         $profile_link = '';
527                 }
528
529                 if ($sparkle) {
530                         $status_link = $profile_link . '?url=status';
531                         $photos_link = $profile_link . '?url=photos';
532                         $profile_link = $profile_link . '?url=profile';
533                 }
534
535                 if (in_array($contact['network'], [NETWORK_DFRN, NETWORK_DIASPORA])) {
536                         $pm_url = System::baseUrl() . '/message/new/' . $contact['id'];
537                 }
538
539                 if ($contact['network'] == NETWORK_DFRN) {
540                         $poke_link = System::baseUrl() . '/poke/?f=&c=' . $contact['id'];
541                 }
542
543                 $contact_url = System::baseUrl() . '/contacts/' . $contact['id'];
544
545                 $posts_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/posts';
546                 $contact_drop_link = System::baseUrl() . '/contacts/' . $contact['id'] . '/drop?confirm=1';
547
548                 /**
549                  * Menu array:
550                  * "name" => [ "Label", "link", (bool)Should the link opened in a new tab? ]
551                  */
552                 $menu = [
553                         'status'  => [L10n::t("View Status")  , $status_link      , true],
554                         'profile' => [L10n::t("View Profile") , $profile_link     , true],
555                         'photos'  => [L10n::t("View Photos")  , $photos_link      , true],
556                         'network' => [L10n::t("Network Posts"), $posts_link       , false],
557                         'edit'    => [L10n::t("View Contact") , $contact_url      , false],
558                         'drop'    => [L10n::t("Drop Contact") , $contact_drop_link, false],
559                         'pm'      => [L10n::t("Send PM")      , $pm_url           , false],
560                         'poke'    => [L10n::t("Poke")         , $poke_link        , false],
561                 ];
562
563                 $args = ['contact' => $contact, 'menu' => &$menu];
564
565                 Addon::callHooks('contact_photo_menu', $args);
566
567                 $menucondensed = [];
568
569                 foreach ($menu as $menuname => $menuitem) {
570                         if ($menuitem[1] != '') {
571                                 $menucondensed[$menuname] = $menuitem;
572                         }
573                 }
574
575                 return $menucondensed;
576         }
577
578         /**
579          * @brief Returns ungrouped contact count or list for user
580          *
581          * Returns either the total number of ungrouped contacts for the given user
582          * id or a paginated list of ungrouped contacts.
583          *
584          * @param int $uid   uid
585          * @param int $start optional, default 0
586          * @param int $count optional, default 0
587          *
588          * @return array
589          */
590         public static function getUngroupedList($uid, $start = 0, $count = 0)
591         {
592                 if (!$count) {
593                         $r = q(
594                                 "SELECT COUNT(*) AS `total`
595                                  FROM `contact`
596                                  WHERE `uid` = %d
597                                  AND NOT `self`
598                                  AND NOT `blocked`
599                                  AND NOT `pending`
600                                  AND `id` NOT IN (
601                                         SELECT DISTINCT(`contact-id`)
602                                         FROM `group_member`
603                                         WHERE `uid` = %d
604                                 )",
605                                 intval($uid),
606                                 intval($uid)
607                         );
608
609                         return $r;
610                 }
611
612                 $r = q(
613                         "SELECT *
614                         FROM `contact`
615                         WHERE `uid` = %d
616                         AND NOT `self`
617                         AND NOT `blocked`
618                         AND NOT `pending`
619                         AND `id` NOT IN (
620                                 SELECT DISTINCT(`contact-id`)
621                                 FROM `group_member`
622                                 INNER JOIN `group` ON `group`.`id` = `group_member`.`gid`
623                                 WHERE `group`.`uid` = %d
624                         )
625                         LIMIT %d, %d",
626                         intval($uid),
627                         intval($uid),
628                         intval($start),
629                         intval($count)
630                 );
631
632                 return $r;
633         }
634
635         /**
636          * @brief Fetch the contact id for a given URL and user
637          *
638          * First lookup in the contact table to find a record matching either `url`, `nurl`,
639          * `addr` or `alias`.
640          *
641          * If there's no record and we aren't looking for a public contact, we quit.
642          * If there's one, we check that it isn't time to update the picture else we
643          * directly return the found contact id.
644          *
645          * Second, we probe the provided $url whether it's http://server.tld/profile or
646          * nick@server.tld. We quit if we can't get any info back.
647          *
648          * Third, we create the contact record if it doesn't exist
649          *
650          * Fourth, we update the existing record with the new data (avatar, alias, nick)
651          * if there's any updates
652          *
653          * @param string  $url       Contact URL
654          * @param integer $uid       The user id for the contact (0 = public contact)
655          * @param boolean $no_update Don't update the contact
656          *
657          * @return integer Contact ID
658          */
659         public static function getIdForURL($url, $uid = 0, $no_update = false)
660         {
661                 logger("Get contact data for url " . $url . " and user " . $uid . " - " . System::callstack(), LOGGER_DEBUG);
662
663                 $contact_id = 0;
664
665                 if ($url == '') {
666                         return 0;
667                 }
668
669                 /// @todo Verify if we can't use Contact::getDetailsByUrl instead of the following
670                 // We first try the nurl (http://server.tld/nick), most common case
671                 $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['nurl' => normalise_link($url), 'uid' => $uid]);
672
673                 // Then the addr (nick@server.tld)
674                 if (!DBM::is_result($contact)) {
675                         $contact = dba::selectFirst('contact', ['id', 'avatar-date'], ['addr' => $url, 'uid' => $uid]);
676                 }
677
678                 // Then the alias (which could be anything)
679                 if (!DBM::is_result($contact)) {
680                         // The link could be provided as http although we stored it as https
681                         $ssl_url = str_replace('http://', 'https://', $url);
682                         $condition = ['`alias` IN (?, ?, ?) AND `uid` = ?', $url, normalise_link($url), $ssl_url, $uid];
683                         $contact = dba::selectFirst('contact', ['id', 'avatar', 'avatar-date'], $condition);
684                 }
685
686                 if (DBM::is_result($contact)) {
687                         $contact_id = $contact["id"];
688
689                         // Update the contact every 7 days
690                         $update_contact = ($contact['avatar-date'] < datetime_convert('', '', 'now -7 days'));
691
692                         // We force the update if the avatar is empty
693                         if (!x($contact, 'avatar')) {
694                                 $update_contact = true;
695                         }
696
697                         if (!$update_contact || $no_update) {
698                                 return $contact_id;
699                         }
700                 } elseif ($uid != 0) {
701                         // Non-existing user-specific contact, exiting
702                         return 0;
703                 }
704
705                 $data = Probe::uri($url, "", $uid);
706
707                 // Last try in gcontact for unsupported networks
708                 if (!in_array($data["network"], [NETWORK_DFRN, NETWORK_OSTATUS, NETWORK_DIASPORA, NETWORK_PUMPIO, NETWORK_MAIL])) {
709                         if ($uid != 0) {
710                                 return 0;
711                         }
712
713                         // Get data from the gcontact table
714                         $gcontact = dba::selectFirst('gcontact', ['name', 'nick', 'url', 'photo', 'addr', 'alias', 'network'], ['nurl' => normalise_link($url)]);
715                         if (!DBM::is_result($gcontact)) {
716                                 return 0;
717                         }
718
719                         $data = array_merge($data, $gcontact);
720                 }
721
722                 if (!$contact_id && ($data["alias"] != '') && ($data["alias"] != $url)) {
723                         $contact_id = self::getIdForURL($data["alias"], $uid, true);
724                 }
725
726                 $url = $data["url"];
727                 if (!$contact_id) {
728                         dba::insert('contact', [
729                                 'uid'       => $uid,
730                                 'created'   => datetime_convert(),
731                                 'url'       => $data["url"],
732                                 'nurl'      => normalise_link($data["url"]),
733                                 'addr'      => $data["addr"],
734                                 'alias'     => $data["alias"],
735                                 'notify'    => $data["notify"],
736                                 'poll'      => $data["poll"],
737                                 'name'      => $data["name"],
738                                 'nick'      => $data["nick"],
739                                 'photo'     => $data["photo"],
740                                 'keywords'  => $data["keywords"],
741                                 'location'  => $data["location"],
742                                 'about'     => $data["about"],
743                                 'network'   => $data["network"],
744                                 'pubkey'    => $data["pubkey"],
745                                 'rel'       => CONTACT_IS_SHARING,
746                                 'priority'  => $data["priority"],
747                                 'batch'     => $data["batch"],
748                                 'request'   => $data["request"],
749                                 'confirm'   => $data["confirm"],
750                                 'poco'      => $data["poco"],
751                                 'name-date' => datetime_convert(),
752                                 'uri-date'  => datetime_convert(),
753                                 'avatar-date' => datetime_convert(),
754                                 'writable'  => 1,
755                                 'blocked'   => 0,
756                                 'readonly'  => 0,
757                                 'pending'   => 0]
758                         );
759
760                         $s = dba::select('contact', ['id'], ['nurl' => normalise_link($data["url"]), 'uid' => $uid], ['order' => ['id'], 'limit' => 2]);
761                         $contacts = dba::inArray($s);
762                         if (!DBM::is_result($contacts)) {
763                                 return 0;
764                         }
765
766                         $contact_id = $contacts[0]["id"];
767
768                         // Update the newly created contact from data in the gcontact table
769                         $gcontact = dba::selectFirst('gcontact', ['location', 'about', 'keywords', 'gender'], ['nurl' => normalise_link($data["url"])]);
770                         if (DBM::is_result($gcontact)) {
771                                 // Only use the information when the probing hadn't fetched these values
772                                 if ($data['keywords'] != '') {
773                                         unset($gcontact['keywords']);
774                                 }
775                                 if ($data['location'] != '') {
776                                         unset($gcontact['location']);
777                                 }
778                                 if ($data['about'] != '') {
779                                         unset($gcontact['about']);
780                                 }
781                                 dba::update('contact', $gcontact, ['id' => $contact_id]);
782                         }
783
784                         if (count($contacts) > 1 && $uid == 0 && $contact_id != 0 && $data["url"] != "") {
785                                 dba::delete('contact', ["`nurl` = ? AND `uid` = 0 AND `id` != ? AND NOT `self`",
786                                         normalise_link($data["url"]), $contact_id]);
787                         }
788                 }
789
790                 self::updateAvatar($data["photo"], $uid, $contact_id);
791
792                 $fields = ['url', 'nurl', 'addr', 'alias', 'name', 'nick', 'keywords', 'location', 'about', 'avatar-date', 'pubkey'];
793                 $contact = dba::selectFirst('contact', $fields, ['id' => $contact_id]);
794
795                 // This condition should always be true
796                 if (!DBM::is_result($contact)) {
797                         return $contact_id;
798                 }
799
800                 $updated = ['addr' => $data['addr'],
801                         'alias' => $data['alias'],
802                         'url' => $data['url'],
803                         'nurl' => normalise_link($data['url']),
804                         'name' => $data['name'],
805                         'nick' => $data['nick']];
806
807                 // Only fill the pubkey if it was empty before. We have to prevent identity theft.
808                 if (!empty($contact['pubkey'])) {
809                         unset($contact['pubkey']);
810                 } else {
811                         $updated['pubkey'] = $data['pubkey'];
812                 }
813
814                 if ($data['keywords'] != '') {
815                         $updated['keywords'] = $data['keywords'];
816                 }
817                 if ($data['location'] != '') {
818                         $updated['location'] = $data['location'];
819                 }
820                 if ($data['about'] != '') {
821                         $updated['about'] = $data['about'];
822                 }
823
824                 if (($data["addr"] != $contact["addr"]) || ($data["alias"] != $contact["alias"])) {
825                         $updated['uri-date'] = datetime_convert();
826                 }
827                 if (($data["name"] != $contact["name"]) || ($data["nick"] != $contact["nick"])) {
828                         $updated['name-date'] = datetime_convert();
829                 }
830
831                 $updated['avatar-date'] = datetime_convert();
832
833                 dba::update('contact', $updated, ['id' => $contact_id], $contact);
834
835                 return $contact_id;
836         }
837
838         /**
839          * @brief Checks if the contact is blocked
840          *
841          * @param int $cid contact id
842          *
843          * @return boolean Is the contact blocked?
844          */
845         public static function isBlocked($cid)
846         {
847                 if ($cid == 0) {
848                         return false;
849                 }
850
851                 $blocked = dba::selectFirst('contact', ['blocked'], ['id' => $cid]);
852                 if (!DBM::is_result($blocked)) {
853                         return false;
854                 }
855                 return (bool) $blocked['blocked'];
856         }
857
858         /**
859          * @brief Checks if the contact is hidden
860          *
861          * @param int $cid contact id
862          *
863          * @return boolean Is the contact hidden?
864          */
865         public static function isHidden($cid)
866         {
867                 if ($cid == 0) {
868                         return false;
869                 }
870
871                 $hidden = dba::selectFirst('contact', ['hidden'], ['id' => $cid]);
872                 if (!DBM::is_result($hidden)) {
873                         return false;
874                 }
875                 return (bool) $hidden['hidden'];
876         }
877
878         /**
879          * @brief Returns posts from a given contact url
880          *
881          * @param string $contact_url Contact URL
882          *
883          * @return string posts in HTML
884          */
885         public static function getPostsFromUrl($contact_url)
886         {
887                 $a = self::getApp();
888
889                 require_once 'include/conversation.php';
890
891                 // There are no posts with "uid = 0" with connector networks
892                 // This speeds up the query a lot
893                 $r = q("SELECT `network`, `id` AS `author-id`, `contact-type` FROM `contact`
894                         WHERE `contact`.`nurl` = '%s' AND `contact`.`uid` = 0",
895                         dbesc(normalise_link($contact_url))
896                 );
897
898                 if (!DBM::is_result($r)) {
899                         return '';
900                 }
901
902                 if (in_array($r[0]["network"], [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS, ""])) {
903                         $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = %d AND NOT `item`.`global`))";
904                 } else {
905                         $sql = "`item`.`uid` = %d";
906                 }
907
908                 $author_id = intval($r[0]["author-id"]);
909
910                 $contact = ($r[0]["contact-type"] == ACCOUNT_TYPE_COMMUNITY ? 'owner-id' : 'author-id');
911
912                 $r = q(item_query() . " AND `item`.`" . $contact . "` = %d AND " . $sql .
913                         " AND `item`.`verb` = '%s' ORDER BY `item`.`created` DESC LIMIT %d, %d",
914                         intval($author_id), intval(local_user()), dbesc(ACTIVITY_POST),
915                         intval($a->pager['start']), intval($a->pager['itemspage'])
916                 );
917
918                 $o = conversation($a, $r, 'contact-posts', false);
919
920                 $o .= alt_pager($a, count($r));
921
922                 return $o;
923         }
924
925         /**
926          * @brief Returns the account type name
927          *
928          * The function can be called with either the user or the contact array
929          *
930          * @param array $contact contact or user array
931          * @return string
932          */
933         public static function getAccountType(array $contact)
934         {
935                 // There are several fields that indicate that the contact or user is a forum
936                 // "page-flags" is a field in the user table,
937                 // "forum" and "prv" are used in the contact table. They stand for PAGE_COMMUNITY and PAGE_PRVGROUP.
938                 // "community" is used in the gcontact table and is true if the contact is PAGE_COMMUNITY or PAGE_PRVGROUP.
939                 if ((isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_COMMUNITY))
940                         || (isset($contact['page-flags']) && (intval($contact['page-flags']) == PAGE_PRVGROUP))
941                         || (isset($contact['forum']) && intval($contact['forum']))
942                         || (isset($contact['prv']) && intval($contact['prv']))
943                         || (isset($contact['community']) && intval($contact['community']))
944                 ) {
945                         $type = ACCOUNT_TYPE_COMMUNITY;
946                 } else {
947                         $type = ACCOUNT_TYPE_PERSON;
948                 }
949
950                 // The "contact-type" (contact table) and "account-type" (user table) are more general then the chaos from above.
951                 if (isset($contact["contact-type"])) {
952                         $type = $contact["contact-type"];
953                 }
954
955                 if (isset($contact["account-type"])) {
956                         $type = $contact["account-type"];
957                 }
958
959                 switch ($type) {
960                         case ACCOUNT_TYPE_ORGANISATION:
961                                 $account_type = L10n::t("Organisation");
962                                 break;
963                         case ACCOUNT_TYPE_NEWS:
964                                 $account_type = L10n::t('News');
965                                 break;
966                         case ACCOUNT_TYPE_COMMUNITY:
967                                 $account_type = L10n::t("Forum");
968                                 break;
969                         default:
970                                 $account_type = "";
971                                 break;
972                 }
973
974                 return $account_type;
975         }
976
977         /**
978          * @brief Blocks a contact
979          *
980          * @param int $uid
981          * @return bool
982          */
983         public static function block($uid)
984         {
985                 $return = dba::update('contact', ['blocked' => true], ['id' => $uid]);
986
987                 return $return;
988         }
989
990         /**
991          * @brief Unblocks a contact
992          *
993          * @param int $uid
994          * @return bool
995          */
996         public static function unblock($uid)
997         {
998                 $return = dba::update('contact', ['blocked' => false], ['id' => $uid]);
999
1000                 return $return;
1001         }
1002
1003         /**
1004          * @brief Updates the avatar links in a contact only if needed
1005          *
1006          * @param string $avatar Link to avatar picture
1007          * @param int    $uid    User id of contact owner
1008          * @param int    $cid    Contact id
1009          * @param bool   $force  force picture update
1010          *
1011          * @return array Returns array of the different avatar sizes
1012          */
1013         public static function updateAvatar($avatar, $uid, $cid, $force = false)
1014         {
1015                 $contact = dba::selectFirst('contact', ['avatar', 'photo', 'thumb', 'micro', 'nurl'], ['id' => $cid]);
1016                 if (!DBM::is_result($contact)) {
1017                         return false;
1018                 } else {
1019                         $data = [$contact["photo"], $contact["thumb"], $contact["micro"]];
1020                 }
1021
1022                 if (($contact["avatar"] != $avatar) || $force) {
1023                         $photos = Photo::importProfilePhoto($avatar, $uid, $cid, true);
1024
1025                         if ($photos) {
1026                                 dba::update(
1027                                         'contact',
1028                                         ['avatar' => $avatar, 'photo' => $photos[0], 'thumb' => $photos[1], 'micro' => $photos[2], 'avatar-date' => datetime_convert()],
1029                                         ['id' => $cid]
1030                                 );
1031
1032                                 // Update the public contact (contact id = 0)
1033                                 if ($uid != 0) {
1034                                         $pcontact = dba::selectFirst('contact', ['id'], ['nurl' => $contact['nurl']]);
1035                                         if (DBM::is_result($pcontact)) {
1036                                                 self::updateAvatar($avatar, 0, $pcontact['id'], $force);
1037                                         }
1038                                 }
1039
1040                                 return $photos;
1041                         }
1042                 }
1043
1044                 return $data;
1045         }
1046
1047         /**
1048          * @param integer $id contact id
1049          * @return boolean
1050          */
1051         public static function updateFromProbe($id)
1052         {
1053                 /*
1054                   Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
1055                   This will reliably kill your communication with Friendica contacts.
1056                  */
1057
1058                 $fields = ['url', 'nurl', 'addr', 'alias', 'batch', 'notify', 'poll', 'poco', 'network'];
1059                 $contact = dba::selectFirst('contact', $fields, ['id' => $id]);
1060                 if (!DBM::is_result($contact)) {
1061                         return false;
1062                 }
1063
1064                 $ret = Probe::uri($contact["url"]);
1065
1066                 // If Probe::uri fails the network code will be different
1067                 if ($ret["network"] != $contact["network"]) {
1068                         return false;
1069                 }
1070
1071                 $update = false;
1072
1073                 // make sure to not overwrite existing values with blank entries
1074                 foreach ($ret as $key => $val) {
1075                         if (isset($contact[$key]) && ($contact[$key] != "") && ($val == "")) {
1076                                 $ret[$key] = $contact[$key];
1077                         }
1078
1079                         if (isset($contact[$key]) && ($ret[$key] != $contact[$key])) {
1080                                 $update = true;
1081                         }
1082                 }
1083
1084                 if (!$update) {
1085                         return true;
1086                 }
1087
1088                 dba::update(
1089                         'contact', [
1090                                 'url'    => $ret['url'],
1091                                 'nurl'   => normalise_link($ret['url']),
1092                                 'addr'   => $ret['addr'],
1093                                 'alias'  => $ret['alias'],
1094                                 'batch'  => $ret['batch'],
1095                                 'notify' => $ret['notify'],
1096                                 'poll'   => $ret['poll'],
1097                                 'poco'   => $ret['poco']
1098                         ],
1099                         ['id' => $id]
1100                 );
1101
1102                 // Update the corresponding gcontact entry
1103                 PortableContact::lastUpdated($ret["url"]);
1104
1105                 return true;
1106         }
1107
1108         /**
1109          * Takes a $uid and a url/handle and adds a new contact
1110          * Currently if the contact is DFRN, interactive needs to be true, to redirect to the
1111          * dfrn_request page.
1112          *
1113          * Otherwise this can be used to bulk add StatusNet contacts, Twitter contacts, etc.
1114          *
1115          * Returns an array
1116          * $return['success'] boolean true if successful
1117          * $return['message'] error text if success is false.
1118          *
1119          * @brief Takes a $uid and a url/handle and adds a new contact
1120          * @param int    $uid
1121          * @param string $url
1122          * @param bool   $interactive
1123          * @param string $network
1124          * @return boolean|string
1125          */
1126         public static function createFromProbe($uid, $url, $interactive = false, $network = '')
1127         {
1128                 $result = ['cid' => -1, 'success' => false, 'message' => ''];
1129
1130                 $a = get_app();
1131
1132                 // remove ajax junk, e.g. Twitter
1133                 $url = str_replace('/#!/', '/', $url);
1134
1135                 if (!Network::isUrlAllowed($url)) {
1136                         $result['message'] = L10n::t('Disallowed profile URL.');
1137                         return $result;
1138                 }
1139
1140                 if (Network::isUrlBlocked($url)) {
1141                         $result['message'] = L10n::t('Blocked domain');
1142                         return $result;
1143                 }
1144
1145                 if (!$url) {
1146                         $result['message'] = L10n::t('Connect URL missing.');
1147                         return $result;
1148                 }
1149
1150                 $arr = ['url' => $url, 'contact' => []];
1151
1152                 Addon::callHooks('follow', $arr);
1153
1154                 if (x($arr['contact'], 'name')) {
1155                         $ret = $arr['contact'];
1156                 } else {
1157                         $ret = Probe::uri($url, $network, $uid, false);
1158                 }
1159
1160                 if (($network != '') && ($ret['network'] != $network)) {
1161                         logger('Expected network ' . $network . ' does not match actual network ' . $ret['network']);
1162                         return result;
1163                 }
1164
1165                 if ($ret['network'] === NETWORK_DFRN) {
1166                         if ($interactive) {
1167                                 if (strlen($a->path)) {
1168                                         $myaddr = bin2hex(System::baseUrl() . '/profile/' . $a->user['nickname']);
1169                                 } else {
1170                                         $myaddr = bin2hex($a->user['nickname'] . '@' . $a->get_hostname());
1171                                 }
1172
1173                                 goaway($ret['request'] . "&addr=$myaddr");
1174
1175                                 // NOTREACHED
1176                         }
1177                 } elseif (Config::get('system', 'dfrn_only')) {
1178                         $result['message'] = L10n::t('This site is not configured to allow communications with other networks.') . EOL;
1179                         $result['message'] != L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1180                         return $result;
1181                 }
1182
1183                 // This extra param just confuses things, remove it
1184                 if ($ret['network'] === NETWORK_DIASPORA) {
1185                         $ret['url'] = str_replace('?absolute=true', '', $ret['url']);
1186                 }
1187
1188                 // do we have enough information?
1189
1190                 if (!((x($ret, 'name')) && (x($ret, 'poll')) && ((x($ret, 'url')) || (x($ret, 'addr'))))) {
1191                         $result['message'] .= L10n::t('The profile address specified does not provide adequate information.') . EOL;
1192                         if (!x($ret, 'poll')) {
1193                                 $result['message'] .= L10n::t('No compatible communication protocols or feeds were discovered.') . EOL;
1194                         }
1195                         if (!x($ret, 'name')) {
1196                                 $result['message'] .= L10n::t('An author or name was not found.') . EOL;
1197                         }
1198                         if (!x($ret, 'url')) {
1199                                 $result['message'] .= L10n::t('No browser URL could be matched to this address.') . EOL;
1200                         }
1201                         if (strpos($url, '@') !== false) {
1202                                 $result['message'] .= L10n::t('Unable to match @-style Identity Address with a known protocol or email contact.') . EOL;
1203                                 $result['message'] .= L10n::t('Use mailto: in front of address to force email check.') . EOL;
1204                         }
1205                         return $result;
1206                 }
1207
1208                 if ($ret['network'] === NETWORK_OSTATUS && Config::get('system', 'ostatus_disabled')) {
1209                         $result['message'] .= L10n::t('The profile address specified belongs to a network which has been disabled on this site.') . EOL;
1210                         $ret['notify'] = '';
1211                 }
1212
1213                 if (!$ret['notify']) {
1214                         $result['message'] .= L10n::t('Limited profile. This person will be unable to receive direct/personal notifications from you.') . EOL;
1215                 }
1216
1217                 $writeable = ((($ret['network'] === NETWORK_OSTATUS) && ($ret['notify'])) ? 1 : 0);
1218
1219                 $subhub = (($ret['network'] === NETWORK_OSTATUS) ? true : false);
1220
1221                 $hidden = (($ret['network'] === NETWORK_MAIL) ? 1 : 0);
1222
1223                 if (in_array($ret['network'], [NETWORK_MAIL, NETWORK_DIASPORA])) {
1224                         $writeable = 1;
1225                 }
1226
1227                 // check if we already have a contact
1228                 // the poll url is more reliable than the profile url, as we may have
1229                 // indirect links or webfinger links
1230
1231                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `poll` IN ('%s', '%s') AND `network` = '%s' LIMIT 1",
1232                         intval($uid),
1233                         dbesc($ret['poll']),
1234                         dbesc(normalise_link($ret['poll'])),
1235                         dbesc($ret['network'])
1236                 );
1237
1238                 if (!DBM::is_result($r)) {
1239                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` = '%s' LIMIT 1",
1240                                 intval($uid),
1241                                 dbesc(normalise_link($url)),
1242                                 dbesc($ret['network'])
1243                         );
1244                 }
1245
1246                 if (DBM::is_result($r)) {
1247                         // update contact
1248                         $new_relation = (($r[0]['rel'] == CONTACT_IS_FOLLOWER) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1249
1250                         $fields = ['rel' => $new_relation, 'subhub' => $subhub, 'readonly' => false];
1251                         dba::update('contact', $fields, ['id' => $r[0]['id']]);
1252                 } else {
1253                         $new_relation = ((in_array($ret['network'], [NETWORK_MAIL])) ? CONTACT_IS_FRIEND : CONTACT_IS_SHARING);
1254
1255                         // create contact record
1256                         dba::insert('contact', [
1257                                 'uid'     => $uid,
1258                                 'created' => datetime_convert(),
1259                                 'url'     => $ret['url'],
1260                                 'nurl'    => normalise_link($ret['url']),
1261                                 'addr'    => $ret['addr'],
1262                                 'alias'   => $ret['alias'],
1263                                 'batch'   => $ret['batch'],
1264                                 'notify'  => $ret['notify'],
1265                                 'poll'    => $ret['poll'],
1266                                 'poco'    => $ret['poco'],
1267                                 'name'    => $ret['name'],
1268                                 'nick'    => $ret['nick'],
1269                                 'network' => $ret['network'],
1270                                 'pubkey'  => $ret['pubkey'],
1271                                 'rel'     => $new_relation,
1272                                 'priority'=> $ret['priority'],
1273                                 'writable'=> $writeable,
1274                                 'hidden'  => $hidden,
1275                                 'blocked' => 0,
1276                                 'readonly'=> 0,
1277                                 'pending' => 0,
1278                                 'subhub'  => $subhub
1279                         ]);
1280                 }
1281
1282                 $contact = dba::selectFirst('contact', [], ['url' => $ret['url'], 'network' => $ret['network'], 'uid' => $uid]);
1283                 if (!DBM::is_result($contact)) {
1284                         $result['message'] .= L10n::t('Unable to retrieve contact information.') . EOL;
1285                         return $result;
1286                 }
1287
1288                 $contact_id = $contact['id'];
1289                 $result['cid'] = $contact_id;
1290
1291                 Group::addMember(User::getDefaultGroup($uid, $contact["network"]), $contact_id);
1292
1293                 // Update the avatar
1294                 self::updateAvatar($ret['photo'], $uid, $contact_id);
1295
1296                 // pull feed and consume it, which should subscribe to the hub.
1297
1298                 Worker::add(PRIORITY_HIGH, "OnePoll", $contact_id, "force");
1299
1300                 $r = q("SELECT `contact`.*, `user`.* FROM `contact` INNER JOIN `user` ON `contact`.`uid` = `user`.`uid`
1301                         WHERE `user`.`uid` = %d AND `contact`.`self` LIMIT 1",
1302                         intval($uid)
1303                 );
1304
1305                 if (DBM::is_result($r)) {
1306                         if (($contact['network'] == NETWORK_OSTATUS) && (strlen($contact['notify']))) {
1307                                 // create a follow slap
1308                                 $item = [];
1309                                 $item['verb'] = ACTIVITY_FOLLOW;
1310                                 $item['follow'] = $contact["url"];
1311                                 $slap = OStatus::salmon($item, $r[0]);
1312                                 Salmon::slapper($r[0], $contact['notify'], $slap);
1313                         }
1314
1315                         if ($contact['network'] == NETWORK_DIASPORA) {
1316                                 $ret = Diaspora::sendShare($a->user, $contact);
1317                                 logger('share returns: ' . $ret);
1318                         }
1319                 }
1320
1321                 $result['success'] = true;
1322                 return $result;
1323         }
1324
1325         public static function updateSslPolicy($contact, $new_policy)
1326         {
1327                 $ssl_changed = false;
1328                 if ((intval($new_policy) == SSL_POLICY_SELFSIGN || $new_policy === 'self') && strstr($contact['url'], 'https:')) {
1329                         $ssl_changed = true;
1330                         $contact['url']     =   str_replace('https:', 'http:', $contact['url']);
1331                         $contact['request'] =   str_replace('https:', 'http:', $contact['request']);
1332                         $contact['notify']  =   str_replace('https:', 'http:', $contact['notify']);
1333                         $contact['poll']    =   str_replace('https:', 'http:', $contact['poll']);
1334                         $contact['confirm'] =   str_replace('https:', 'http:', $contact['confirm']);
1335                         $contact['poco']    =   str_replace('https:', 'http:', $contact['poco']);
1336                 }
1337
1338                 if ((intval($new_policy) == SSL_POLICY_FULL || $new_policy === 'full') && strstr($contact['url'], 'http:')) {
1339                         $ssl_changed = true;
1340                         $contact['url']     =   str_replace('http:', 'https:', $contact['url']);
1341                         $contact['request'] =   str_replace('http:', 'https:', $contact['request']);
1342                         $contact['notify']  =   str_replace('http:', 'https:', $contact['notify']);
1343                         $contact['poll']    =   str_replace('http:', 'https:', $contact['poll']);
1344                         $contact['confirm'] =   str_replace('http:', 'https:', $contact['confirm']);
1345                         $contact['poco']    =   str_replace('http:', 'https:', $contact['poco']);
1346                 }
1347
1348                 if ($ssl_changed) {
1349                         $fields = ['url' => $contact['url'], 'request' => $contact['request'],
1350                                         'notify' => $contact['notify'], 'poll' => $contact['poll'],
1351                                         'confirm' => $contact['confirm'], 'poco' => $contact['poco']];
1352                         dba::update('contact', $fields, ['id' => $contact['id']]);
1353                 }
1354
1355                 return $contact;
1356         }
1357 }