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