]> git.mxchange.org Git - friendica.git/commitdiff
Merge remote-tracking branch 'upstream/2018.08-rc' into ap1
authorMichael <heluecht@pirati.ca>
Sat, 15 Sep 2018 20:49:46 +0000 (20:49 +0000)
committerMichael <heluecht@pirati.ca>
Sat, 15 Sep 2018 20:49:46 +0000 (20:49 +0000)
20 files changed:
include/conversation.php
mod/contacts.php
mod/dfrn_confirm.php
mod/dirfind.php
mod/display.php
mod/follow.php
mod/profile.php
mod/xrd.php
src/Content/ContactSelector.php
src/Content/Widget.php
src/Model/Contact.php
src/Model/Conversation.php
src/Model/Item.php
src/Module/Inbox.php [new file with mode: 0644]
src/Network/Probe.php
src/Protocol/ActivityPub.php [new file with mode: 0644]
src/Protocol/Diaspora.php
src/Protocol/PortableContact.php
src/Worker/Notifier.php
src/Worker/UpdateGContact.php

index 45e5d1caa3832ad98e04544a4ca71f2283afab3d..835d2274775f27be7dbd0f6949790f8dab3b6342 100644 (file)
@@ -556,7 +556,7 @@ function conversation(App $a, array $items, $mode, $update, $preview = false, $o
                if (in_array($mode, ['community', 'contacts'])) {
                        $writable = true;
                } else {
-                       $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
+                       $writable = ($items[0]['uid'] == 0) && in_array($items[0]['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
                }
 
                if (!local_user()) {
@@ -807,7 +807,7 @@ function conversation_add_children(array $parents, $block_authors, $order, $uid)
 
        foreach ($items as $index => $item) {
                if ($item['uid'] == 0) {
-                       $items[$index]['writable'] = in_array($item['network'], [Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
+                       $items[$index]['writable'] = in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::DFRN]);
                }
        }
 
@@ -877,7 +877,7 @@ function item_photo_menu($item) {
                }
 
                if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
-                       in_array($item['network'], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
+                       in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
                        $menu[L10n::t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']);
                }
        } else {
index 1604f0b6605ec43d6f0e936972ad2394a45c11f2..a7c67cb910aa2964e456d967448a9040731eb34c 100644 (file)
@@ -542,7 +542,7 @@ function contacts_content(App $a, $update = 0)
                        $relation_text = '';
                }
 
-               if (!in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
+               if (!in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA])) {
                        $relation_text = "";
                }
 
@@ -564,7 +564,7 @@ function contacts_content(App $a, $update = 0)
                }
                $lblsuggest = (($contact['network'] === Protocol::DFRN) ? L10n::t('Suggest friends') : '');
 
-               $poll_enabled = in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL]);
+               $poll_enabled = in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL]);
 
                $nettype = L10n::t('Network type: %s', ContactSelector::networkToName($contact['network'], $contact["url"]));
 
@@ -975,7 +975,7 @@ function contact_conversations(App $a, $contact_id, $update)
                $profiledata = Contact::getDetailsByURL($contact["url"]);
 
                if (local_user()) {
-                       if (in_array($profiledata["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
+                       if (in_array($profiledata["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
                                $profiledata["remoteconnect"] = System::baseUrl()."/follow?url=".urlencode($profiledata["url"]);
                        }
                }
@@ -999,7 +999,7 @@ function contact_posts(App $a, $contact_id)
                $profiledata = Contact::getDetailsByURL($contact["url"]);
 
                if (local_user()) {
-                       if (in_array($profiledata["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
+                       if (in_array($profiledata["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
                                $profiledata["remoteconnect"] = System::baseUrl()."/follow?url=".urlencode($profiledata["url"]);
                        }
                }
@@ -1080,7 +1080,7 @@ function _contact_detail_for_template(array $rr)
  */
 function contact_actions($contact)
 {
-       $poll_enabled = in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL]);
+       $poll_enabled = in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::FEED, Protocol::MAIL]);
        $contact_actions = [];
 
        // Provide friend suggestion only for Friendica contacts
index 41b5e0ef54f16587dae6e2935ad40916b801e519..4abaf978fb7f99d0e319690258f6f07f9952f973 100644 (file)
@@ -28,6 +28,7 @@ use Friendica\Model\Group;
 use Friendica\Model\User;
 use Friendica\Network\Probe;
 use Friendica\Protocol\Diaspora;
+use Friendica\Protocol\ActivityPub;
 use Friendica\Util\Crypto;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
@@ -335,10 +336,17 @@ function dfrn_confirm_post(App $a, $handsfree = null)
                                intval($contact_id)
                        );
                } else {
+                       if ($network == Protocol::ACTIVITYPUB) {
+                               ActivityPub::transmitContactAccept($contact['url'], $contact['hub-verify'], $uid);
+                               $pending = true;
+                       } else {
+                               $pending = false;
+                       }
+
                        // $network !== Protocol::DFRN
                        $network = defaults($contact, 'network', Protocol::OSTATUS);
 
-                       $arr = Probe::uri($contact['url']);
+                       $arr = Probe::uri($contact['url'], $network);
 
                        $notify  = defaults($contact, 'notify' , $arr['notify']);
                        $poll    = defaults($contact, 'poll'   , $arr['poll']);
@@ -362,30 +370,12 @@ function dfrn_confirm_post(App $a, $handsfree = null)
 
                        DBA::delete('intro', ['id' => $intro_id]);
 
-                       $r = q("UPDATE `contact` SET `name-date` = '%s',
-                               `uri-date` = '%s',
-                               `addr` = '%s',
-                               `notify` = '%s',
-                               `poll` = '%s',
-                               `blocked` = 0,
-                               `pending` = 0,
-                               `network` = '%s',
-                               `writable` = %d,
-                               `hidden` = %d,
-                               `rel` = %d
-                               WHERE `id` = %d
-                       ",
-                               DBA::escape(DateTimeFormat::utcNow()),
-                               DBA::escape(DateTimeFormat::utcNow()),
-                               DBA::escape($addr),
-                               DBA::escape($notify),
-                               DBA::escape($poll),
-                               DBA::escape($network),
-                               intval($writable),
-                               intval($hidden),
-                               intval($new_relation),
-                               intval($contact_id)
-                       );
+                       $fields = ['name-date' => DateTimeFormat::utcNow(),
+                               'uri-date' => DateTimeFormat::utcNow(), 'addr' => $addr,
+                               'notify' => $notify, 'poll' => $poll, 'blocked' => false,
+                               'pending' => $pending, 'network' => $network,
+                               'writable' => $writable, 'hidden' => $hidden, 'rel' => $new_relation];
+                       DBA::update('contact', $fields, ['id' => $contact_id]);
                }
 
                if (!DBA::isResult($r)) {
index 332fe90f6c48cf5af9b0a170fb8e6783b2b2581a..4223bb6ecd34bb3e196f9c1a62acbee7ab536810 100644 (file)
@@ -54,7 +54,7 @@ function dirfind_content(App $a, $prefix = "") {
                if ((valid_email($search) && Network::isEmailDomainValid($search)) ||
                        (substr(normalise_link($search), 0, 7) == "http://")) {
                        $user_data = Probe::uri($search);
-                       $discover_user = (in_array($user_data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA]));
+                       $discover_user = (in_array($user_data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA]));
                }
        }
 
index 907bf8ebba50d16b54ff34e341fe56c9e3da9408..21e28d5617250d2e76e38595a678ff7d63b0ffe8 100644 (file)
@@ -17,6 +17,7 @@ use Friendica\Model\Group;
 use Friendica\Model\Item;
 use Friendica\Model\Profile;
 use Friendica\Protocol\DFRN;
+use Friendica\Protocol\ActivityPub;
 
 function display_init(App $a)
 {
@@ -43,7 +44,7 @@ function display_init(App $a)
 
        $item = null;
 
-       $fields = ['id', 'parent', 'author-id', 'body', 'uid'];
+       $fields = ['id', 'parent', 'author-id', 'body', 'uid', 'guid'];
 
        // If there is only one parameter, then check if this parameter could be a guid
        if ($a->argc == 2) {
@@ -76,6 +77,14 @@ function display_init(App $a)
                displayShowFeed($item["id"], false);
        }
 
+       if (stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json')) {
+               $wall_item = Item::selectFirst(['id', 'uid'], ['guid' => $item['guid'], 'wall' => true]);
+               if ($wall_item['uid'] == 180) {
+                       $data = ActivityPub::createActivityFromItem($wall_item['id']);
+                       echo json_encode($data);
+                       exit();
+               }
+       }
        if ($item["id"] != $item["parent"]) {
                $item = Item::selectFirstForUser(local_user(), $fields, ['id' => $item["parent"]]);
        }
index 627ab52033049065a9d737fdf8c725068215c121..65028a70e007fb1d7f4c2e61c74cc921aa7e2840 100644 (file)
@@ -31,7 +31,8 @@ function follow_post(App $a)
        // This is just a precaution if maybe this page is called somewhere directly via POST
        $_SESSION['fastlane'] = $url;
 
-       $result = Contact::createFromProbe($uid, $url, true);
+       $result = Contact::createFromProbe($uid, $url, true, Protocol::ACTIVITYPUB);
+//     $result = Contact::createFromProbe($uid, $url, true);
 
        if ($result['success'] == false) {
                if ($result['message']) {
index 2e3ccd28c52a8769f57c36df7160c841f96c5e45..fd23964e4160906949dc2f1eb5d715452c655987 100644 (file)
@@ -20,6 +20,7 @@ use Friendica\Model\Profile;
 use Friendica\Module\Login;
 use Friendica\Protocol\DFRN;
 use Friendica\Util\DateTimeFormat;
+use Friendica\Protocol\ActivityPub;
 
 function profile_init(App $a)
 {
@@ -49,6 +50,15 @@ function profile_init(App $a)
                DFRN::autoRedir($a, $which);
        }
 
+       if (stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json')) {
+               $user = DBA::selectFirst('user', ['uid'], ['nickname' => $which]);
+               if ($user['uid'] == 180) {
+                       $data = ActivityPub::profile($user['uid']);
+                       echo json_encode($data);
+                       exit();
+               }
+       }
+
        Profile::load($a, $which, $profile);
 
        $blocked   = !local_user() && !remote_user() && Config::get('system', 'block_public');
index 61505f29966e99d2ea4f66f27d2cb091a8bf16cc..87766ca26e5890d7d33605c82c29d70e517181be 100644 (file)
@@ -92,6 +92,10 @@ function xrd_json($a, $uri, $alias, $profile_url, $r)
                        ['rel' => 'http://purl.org/openwebauth/v1', 'type' => 'application/x-dfrn+json', 'href' => System::baseUrl().'/owa']
                ]
        ];
+       if ($r['uid'] == 180) {
+               $json['links'][] = ['rel' => 'self', 'type' => 'application/activity+json', 'href' => $profile_url];
+       }
+
        echo json_encode($json);
        killme();
 }
index d5efecb8060d420564ea2020417fd70cb5432ed8..6a701f25f355d11b87db1afe07f5222cb3584236 100644 (file)
@@ -75,21 +75,22 @@ class ContactSelector
        public static function networkToName($s, $profile = "")
        {
                $nets = [
-                       Protocol::DFRN      => L10n::t('Friendica'),
-                       Protocol::OSTATUS   => L10n::t('OStatus'),
-                       Protocol::FEED      => L10n::t('RSS/Atom'),
-                       Protocol::MAIL      => L10n::t('Email'),
-                       Protocol::DIASPORA  => L10n::t('Diaspora'),
-                       Protocol::ZOT       => L10n::t('Zot!'),
-                       Protocol::LINKEDIN  => L10n::t('LinkedIn'),
-                       Protocol::XMPP      => L10n::t('XMPP/IM'),
-                       Protocol::MYSPACE   => L10n::t('MySpace'),
-                       Protocol::GPLUS     => L10n::t('Google+'),
-                       Protocol::PUMPIO    => L10n::t('pump.io'),
-                       Protocol::TWITTER   => L10n::t('Twitter'),
-                       Protocol::DIASPORA2 => L10n::t('Diaspora Connector'),
-                       Protocol::STATUSNET => L10n::t('GNU Social Connector'),
-                       Protocol::PNUT      => L10n::t('pnut'),
+                       Protocol::DFRN      =>   L10n::t('Friendica'),
+                       Protocol::OSTATUS   =>   L10n::t('OStatus'),
+                       Protocol::FEED      =>   L10n::t('RSS/Atom'),
+                       Protocol::MAIL      =>   L10n::t('Email'),
+                       Protocol::DIASPORA  =>   L10n::t('Diaspora'),
+                       Protocol::ZOT       =>   L10n::t('Zot!'),
+                       Protocol::LINKEDIN  =>   L10n::t('LinkedIn'),
+                       Protocol::XMPP      =>   L10n::t('XMPP/IM'),
+                       Protocol::MYSPACE   =>   L10n::t('MySpace'),
+                       Protocol::GPLUS     =>   L10n::t('Google+'),
+                       Protocol::PUMPIO    =>   L10n::t('pump.io'),
+                       Protocol::TWITTER   =>   L10n::t('Twitter'),
+                       Protocol::DIASPORA2 =>   L10n::t('Diaspora Connector'),
+                       Protocol::STATUSNET =>   L10n::t('GNU Social Connector'),
+                       Protocol::ACTIVITYPUB => L10n::t('ActivityPub'),
+                       Protocol::PNUT      =>   L10n::t('pnut'),
                ];
 
                Addon::callHooks('network_to_name', $nets);
@@ -99,13 +100,17 @@ class ContactSelector
 
                $networkname = str_replace($search, $replace, $s);
 
-               if ((in_array($s, [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) && ($profile != "")) {
+               if ((in_array($s, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) && ($profile != "")) {
                        $r = DBA::fetchFirst("SELECT `gserver`.`platform` FROM `gcontact`
                                        INNER JOIN `gserver` ON `gserver`.`nurl` = `gcontact`.`server_url`
                                        WHERE `gcontact`.`nurl` = ? AND `platform` != ''", normalise_link($profile));
 
                        if (DBA::isResult($r)) {
                                $networkname = $r['platform'];
+
+                               if ($s == Protocol::ACTIVITYPUB) {
+                                       $networkname .= ' (AP)';
+                               }
                        }
                }
 
index f245f0d95e064819b1b6d4ae4a37cc4540f07a72..faba55b7a860b483e28022e98909d85eaa2cb899 100644 (file)
@@ -142,10 +142,7 @@ class Widget
 
                $nets = array();
                while ($rr = DBA::fetch($r)) {
-                       /// @TODO If 'network' is not there, this triggers an E_NOTICE
-                       if ($rr['network']) {
-                               $nets[] = array('ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network']), 'selected' => (($selected == $rr['network']) ? 'selected' : '' ));
-                       }
+                       $nets[] = array('ref' => $rr['network'], 'name' => ContactSelector::networkToName($rr['network']), 'selected' => (($selected == $rr['network']) ? 'selected' : '' ));
                }
                DBA::close($r);
 
index 1bbc0228a806a46dc7729ef1a852e7d12d53cb81..1e61c0d10d2ed5e7a211348117e17bc57e4bdebd 100644 (file)
@@ -16,6 +16,7 @@ use Friendica\Database\DBA;
 use Friendica\Model\Profile;
 use Friendica\Network\Probe;
 use Friendica\Object\Image;
+use Friendica\Protocol\ActivityPub;
 use Friendica\Protocol\Diaspora;
 use Friendica\Protocol\DFRN;
 use Friendica\Protocol\OStatus;
@@ -555,6 +556,8 @@ class Contact extends BaseObject
                        }
                } elseif ($contact['network'] == Protocol::DIASPORA) {
                        Diaspora::sendUnshare($user, $contact);
+               } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
+                       ActivityPub::transmitContactUndo($contact['url'], '', $user['uid']);
                }
        }
 
@@ -775,7 +778,7 @@ class Contact extends BaseObject
                }
 
                if ((empty($profile["addr"]) || empty($profile["name"])) && (defaults($profile, "gid", 0) != 0)
-                       && in_array($profile["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
+                       && in_array($profile["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])
                ) {
                        Worker::add(PRIORITY_LOW, "UpdateGContact", $profile["gid"]);
                }
@@ -1054,7 +1057,6 @@ class Contact extends BaseObject
                        if (!x($contact, 'avatar')) {
                                $update_contact = true;
                        }
-
                        if (!$update_contact || $no_update) {
                                return $contact_id;
                        }
@@ -1088,7 +1090,7 @@ class Contact extends BaseObject
                }
 
                // Last try in gcontact for unsupported networks
-               if (!in_array($data["network"], [Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
+               if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::OSTATUS, Protocol::DIASPORA, Protocol::PUMPIO, Protocol::MAIL, Protocol::FEED])) {
                        if ($uid != 0) {
                                return 0;
                        }
@@ -1327,7 +1329,7 @@ class Contact extends BaseObject
                        return '';
                }
 
-               if (in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
+               if (in_array($r[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
                        $sql = "(`item`.`uid` = 0 OR (`item`.`uid` = ? AND NOT `item`.`global`))";
                } else {
                        $sql = "`item`.`uid` = ?";
@@ -1495,10 +1497,11 @@ class Contact extends BaseObject
        }
 
        /**
-        * @param integer $id contact id
+        * @param integer $id      contact id
+        * @param string  $network Optional network we are probing for
         * @return boolean
         */
-       public static function updateFromProbe($id)
+       public static function updateFromProbe($id, $network = '')
        {
                /*
                  Warning: Never ever fetch the public key via Probe::uri and write it into the contacts.
@@ -1511,10 +1514,10 @@ class Contact extends BaseObject
                        return false;
                }
 
-               $ret = Probe::uri($contact["url"]);
+               $ret = Probe::uri($contact["url"], $network);
 
                // If Probe::uri fails the network code will be different
-               if ($ret["network"] != $contact["network"]) {
+               if (($ret["network"] != $contact["network"]) && ($ret["network"] != $network)) {
                        return false;
                }
 
@@ -1537,14 +1540,15 @@ class Contact extends BaseObject
 
                DBA::update(
                        'contact', [
-                               'url'    => $ret['url'],
-                               'nurl'   => normalise_link($ret['url']),
-                               'addr'   => $ret['addr'],
-                               'alias'  => $ret['alias'],
-                               'batch'  => $ret['batch'],
-                               'notify' => $ret['notify'],
-                               'poll'   => $ret['poll'],
-                               'poco'   => $ret['poco']
+                               'url'     => $ret['url'],
+                               'nurl'    => normalise_link($ret['url']),
+                               'network' => $ret['network'],
+                               'addr'    => $ret['addr'],
+                               'alias'   => $ret['alias'],
+                               'batch'   => $ret['batch'],
+                               'notify'  => $ret['notify'],
+                               'poll'    => $ret['poll'],
+                               'poco'    => $ret['poco']
                        ],
                        ['id' => $id]
                );
@@ -1686,7 +1690,7 @@ class Contact extends BaseObject
 
                $hidden = (($ret['network'] === Protocol::MAIL) ? 1 : 0);
 
-               if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA])) {
+               if (in_array($ret['network'], [Protocol::MAIL, Protocol::DIASPORA, Protocol::ACTIVITYPUB])) {
                        $writeable = 1;
                }
 
@@ -1766,6 +1770,9 @@ class Contact extends BaseObject
                        } elseif ($contact['network'] == Protocol::DIASPORA) {
                                $ret = Diaspora::sendShare($a->user, $contact);
                                logger('share returns: ' . $ret);
+                       } elseif ($contact['network'] == Protocol::ACTIVITYPUB) {
+                               $ret = ActivityPub::transmitActivity('Follow', $contact['url'], $uid);
+                               logger('Follow returns: ' . $ret);
                        }
                }
 
@@ -1814,7 +1821,7 @@ class Contact extends BaseObject
                return $contact;
        }
 
-       public static function addRelationship($importer, $contact, $datarray, $item, $sharing = false) {
+       public static function addRelationship($importer, $contact, $datarray, $item = '', $sharing = false) {
                // Should always be set
                if (empty($datarray['author-id'])) {
                        return;
@@ -1827,7 +1834,7 @@ class Contact extends BaseObject
                        return;
                }
 
-               $url = $pub_contact['url'];
+               $url = defaults($datarray, 'author-link', $pub_contact['url']);
                $name = $pub_contact['name'];
                $photo = $pub_contact['photo'];
                $nick = $pub_contact['nick'];
@@ -1839,13 +1846,17 @@ class Contact extends BaseObject
                                DBA::update('contact', ['rel' => self::FRIEND, 'writable' => true],
                                                ['id' => $contact['id'], 'uid' => $importer['uid']]);
                        }
+
+                       if ($contact['network'] == Protocol::ACTIVITYPUB) {
+                               ActivityPub::transmitContactAccept($contact['url'], $contact['hub-verify'], $importer['uid']);
+                       }
+
                        // send email notification to owner?
                } else {
                        if (DBA::exists('contact', ['nurl' => normalise_link($url), 'uid' => $importer['uid'], 'pending' => true])) {
                                logger('ignoring duplicated connection request from pending contact ' . $url);
                                return;
                        }
-
                        // create contact record
                        q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `name`, `nick`, `photo`, `network`, `rel`,
                                `blocked`, `readonly`, `pending`, `writable`)
index 0692a7341234f66f81530474270af6e4a64f85e8..ba50dc25e4345d0aff29e720b8b82ee81d67be5c 100644 (file)
@@ -22,6 +22,7 @@ class Conversation
        const PARCEL_DIASPORA           = 2;
        const PARCEL_SALMON             = 3;
        const PARCEL_FEED               = 4; // Deprecated
+       const PARCEL_ACTIVITYPUB        = 5;
        const PARCEL_SPLIT_CONVERSATION = 6;
        const PARCEL_TWITTER            = 67;
 
@@ -34,7 +35,7 @@ class Conversation
        public static function insert(array $arr)
        {
                if (in_array(defaults($arr, 'network', Protocol::PHANTOM),
-                               [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::TWITTER]) && !empty($arr['uri'])) {
+                       [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, Protocol::TWITTER]) && !empty($arr['uri'])) {
                        $conversation = ['item-uri' => $arr['uri'], 'received' => DateTimeFormat::utcNow()];
 
                        if (isset($arr['parent-uri']) && ($arr['parent-uri'] != $arr['uri'])) {
@@ -70,7 +71,8 @@ class Conversation
                                        unset($old_conv['source']);
                                }
                                // Update structure data all the time but the source only when its from a better protocol.
-                               if (isset($conversation['protocol']) && isset($conversation['source']) && ($old_conv['protocol'] < $conversation['protocol']) && ($old_conv['protocol'] != 0)) {
+                               if (isset($conversation['protocol']) && isset($conversation['source']) && ($old_conv['protocol'] < $conversation['protocol'])
+                                       && ($old_conv['protocol'] != 0) && ($old_conv['protocol'] != self::PARCEL_ACTIVITYPUB)) {
                                        unset($conversation['protocol']);
                                        unset($conversation['source']);
                                }
index d10a211a59511d98b579583d748c2ff004471a4f..68ebc690e8f7646c282f87f5e4a27bb1a84d6e9e 100644 (file)
@@ -176,7 +176,7 @@ class Item extends BaseObject
 
                // We can always comment on posts from these networks
                if (array_key_exists('writable', $row) &&
-                       in_array($row['internal-network'], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
+                       in_array($row['internal-network'], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
                        $row['writable'] = true;
                }
 
@@ -1352,7 +1352,7 @@ class Item extends BaseObject
                 * We have to check several networks since Friendica posts could be repeated
                 * via OStatus (maybe Diasporsa as well)
                 */
-               if (in_array($item['network'], [Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
+               if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS, ""])) {
                        $condition = ["`uri` = ? AND `uid` = ? AND `network` IN (?, ?, ?)",
                                trim($item['uri']), $item['uid'],
                                Protocol::DIASPORA, Protocol::DFRN, Protocol::OSTATUS];
@@ -2053,7 +2053,7 @@ class Item extends BaseObject
 
                // Only distribute public items from native networks
                $condition = ['id' => $itemid, 'uid' => 0,
-                       'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
+                       'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""],
                        'visible' => true, 'deleted' => false, 'moderated' => false, 'private' => false];
                $item = self::selectFirst(self::ITEM_FIELDLIST, ['id' => $itemid]);
                if (!DBA::isResult($item)) {
@@ -2071,6 +2071,47 @@ class Item extends BaseObject
 
                $users = [];
 
+               $owner = DBA::selectFirst('contact', ['url', 'nurl', 'alias'], ['id' => $parent['owner-id']]);
+               if (!DBA::isResult($owner)) {
+                       return;
+               }
+
+               $condition = ['nurl' => $owner['nurl'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
+               $contacts = DBA::select('contact', ['uid'], $condition);
+               while ($contact = DBA::fetch($contacts)) {
+                       if ($contact['uid'] == 0) {
+                               continue;
+                       }
+
+                       $users[$contact['uid']] = $contact['uid'];
+               }
+               DBA::close($contacts);
+
+               $condition = ['alias' => $owner['url'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
+               $contacts = DBA::select('contact', ['uid'], $condition);
+               while ($contact = DBA::fetch($contacts)) {
+                       if ($contact['uid'] == 0) {
+                               continue;
+                       }
+
+                       $users[$contact['uid']] = $contact['uid'];
+               }
+               DBA::close($contacts);
+
+               if (!empty($owner['alias'])) {
+                       $condition = ['url' => $owner['alias'], 'rel' => [Contact::SHARING, Contact::FRIEND]];
+                       $contacts = DBA::select('contact', ['uid'], $condition);
+                       while ($contact = DBA::fetch($contacts)) {
+                               if ($contact['uid'] == 0) {
+                                       continue;
+                               }
+
+                               $users[$contact['uid']] = $contact['uid'];
+                       }
+                       DBA::close($contacts);
+               }
+/*
+
                $condition = ["`nurl` IN (SELECT `nurl` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
                        $parent['owner-id'], Contact::SHARING,  Contact::FRIEND];
 
@@ -2080,6 +2121,32 @@ class Item extends BaseObject
                        $users[$contact['uid']] = $contact['uid'];
                }
 
+               DBA::close($contacts);
+
+               // And the same with the alias in the user contacts
+               $condition = ["`alias` IN (SELECT `url` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
+                       $parent['owner-id'], Contact::SHARING,  Contact::FRIEND];
+
+               $contacts = DBA::select('contact', ['uid'], $condition);
+
+               while ($contact = DBA::fetch($contacts)) {
+                       $users[$contact['uid']] = $contact['uid'];
+               }
+
+               DBA::close($contacts);
+
+               // And vice versa
+               $condition = ["`url` IN (SELECT `alias` FROM `contact` WHERE `id` = ?) AND `uid` != 0 AND NOT `blocked` AND `rel` IN (?, ?)",
+                       $parent['owner-id'], Contact::SHARING,  Contact::FRIEND];
+
+               $contacts = DBA::select('contact', ['uid'], $condition);
+
+               while ($contact = DBA::fetch($contacts)) {
+                       $users[$contact['uid']] = $contact['uid'];
+               }
+
+               DBA::close($contacts);
+*/
                $origin_uid = 0;
 
                if ($item['uri'] != $item['parent-uri']) {
@@ -2175,7 +2242,7 @@ class Item extends BaseObject
                }
 
                // is it an entry from a connector? Only add an entry for natively connected networks
-               if (!in_array($item["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
+               if (!in_array($item["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS, ""])) {
                        return;
                }
 
@@ -2329,13 +2396,7 @@ class Item extends BaseObject
                        $guid = System::createGUID(32);
                }
 
-               $hostname = self::getApp()->get_hostname();
-
-               $user = DBA::selectFirst('user', ['nickname'], ['uid' => $uid]);
-
-               $uri = "urn:X-dfrn:" . $hostname . ':' . $user['nickname'] . ':' . $guid;
-
-               return $uri;
+               return self::getApp()->get_baseurl() . '/object/' . $guid;
        }
 
        /**
diff --git a/src/Module/Inbox.php b/src/Module/Inbox.php
new file mode 100644 (file)
index 0000000..d47419a
--- /dev/null
@@ -0,0 +1,52 @@
+<?php
+/**
+ * @file src/Module/Inbox.php
+ */
+namespace Friendica\Module;
+
+use Friendica\BaseModule;
+use Friendica\Protocol\ActivityPub;
+use Friendica\Core\System;
+use Friendica\Database\DBA;
+
+/**
+ * ActivityPub Inbox
+ */
+class Inbox extends BaseModule
+{
+       public static function init()
+       {
+               $a = self::getApp();
+
+               $postdata = file_get_contents('php://input');
+
+               if (empty($postdata)) {
+                       System::httpExit(400);
+               }
+
+               if (ActivityPub::verifySignature($postdata, $_SERVER)) {
+                       $filename = 'signed-activitypub';
+               } else {
+                       $filename = 'failed-activitypub';
+               }
+
+               $tempfile = tempnam(get_temppath(), $filename);
+               file_put_contents($tempfile, json_encode(['argv' => $a->argv, 'header' => $_SERVER, 'body' => $postdata]));
+
+               logger('Incoming message stored under ' . $tempfile);
+
+               if (!empty($a->argv[1])) {
+                       $user = DBA::selectFirst('user', ['uid'], ['nickname' => $a->argv[1]]);
+                       if (!DBA::isResult($user)) {
+                               System::httpExit(404);
+                       }
+                       $uid = $user['uid'];
+               } else {
+                       $uid = 0;
+               }
+
+               ActivityPub::processInbox($postdata, $_SERVER, $uid);
+
+               System::httpExit(202);
+       }
+}
index 75231f44ff0bc9e2e1061704cdcbdecc1df1783a..0e9219c5a615b8b095f1068b827f060f640d27c4 100644 (file)
@@ -19,6 +19,7 @@ use Friendica\Model\Contact;
 use Friendica\Model\Profile;
 use Friendica\Protocol\Email;
 use Friendica\Protocol\Feed;
+use Friendica\Protocol\ActivityPub;
 use Friendica\Util\Crypto;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
@@ -328,7 +329,18 @@ class Probe
                        $uid = local_user();
                }
 
-               $data = self::detect($uri, $network, $uid);
+               if ($network != Protocol::ACTIVITYPUB) {
+                       $data = self::detect($uri, $network, $uid);
+               } else {
+                       $data = null;
+               }
+
+               if (in_array(defaults($data, 'network', ''), ['', Protocol::PHANTOM])) {
+                       $ap_profile = ActivityPub::fetchProfile($uri);
+                       if (!empty($ap_profile) && ($ap_profile['network'] == Protocol::ACTIVITYPUB)) {
+                               $data = $ap_profile;
+                       }
+               }
 
                if (!isset($data["url"])) {
                        $data["url"] = $uri;
diff --git a/src/Protocol/ActivityPub.php b/src/Protocol/ActivityPub.php
new file mode 100644 (file)
index 0000000..df6b034
--- /dev/null
@@ -0,0 +1,1181 @@
+<?php
+/**
+ * @file src/Protocol/ActivityPub.php
+ */
+namespace Friendica\Protocol;
+
+use Friendica\Database\DBA;
+use Friendica\Core\System;
+use Friendica\BaseObject;
+use Friendica\Util\Network;
+use Friendica\Util\HTTPSignature;
+use Friendica\Core\Protocol;
+use Friendica\Model\Conversation;
+use Friendica\Model\Contact;
+use Friendica\Model\Item;
+use Friendica\Model\User;
+use Friendica\Util\DateTimeFormat;
+use Friendica\Util\Crypto;
+use Friendica\Content\Text\BBCode;
+use Friendica\Content\Text\HTML;
+use Friendica\Network\Probe;
+
+/**
+ * @brief ActivityPub Protocol class
+ * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
+ * https://www.w3.org/TR/activitypub/
+ * https://www.w3.org/TR/activitystreams-core/
+ * https://www.w3.org/TR/activitystreams-vocabulary/
+ *
+ * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
+ * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
+ *
+ * Digest: https://tools.ietf.org/html/rfc5843
+ * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
+ *
+ * Part of the code for HTTP signing is taken from the Osada project.
+ * 
+ *
+ * To-do:
+ *
+ * Receiver:
+ * - Activities: Dislike, Update, Delete
+ * - Object Types: Person, Tombstome
+ *
+ * Transmitter:
+ * - Activities: Like, Dislike, Update, Delete
+ * - Object Tyoes: Article, Announce, Person, Tombstone
+ *
+ * General:
+ * - Message distribution
+ * - Endpoints: Outbox, Object, Follower, Following
+ */
+class ActivityPub
+{
+       const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
+
+       public static function transmit($data, $target, $uid)
+       {
+               $owner = User::getOwnerDataById($uid);
+
+               if (!$owner) {
+                       return;
+               }
+
+               $content = json_encode($data);
+
+               $host = parse_url($target, PHP_URL_HOST);
+               $path = parse_url($target, PHP_URL_PATH);
+               $date = date('r');
+
+               $headers = ['Host: ' . $host, 'Date: ' . $date];
+
+               $signed_data = "(request-target): post " . $path . "\nhost: " . $host . "\ndate: " . $date;
+
+               $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
+
+               $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",headers="(request-target) host date",signature="' . $signature . '"';
+               $headers[] = 'Content-Type: application/activity+json';
+
+               Network::post($target, $content, $headers);
+               $return_code = BaseObject::getApp()->get_curl_code();
+
+               logger('Transmit to ' . $target . ' returned ' . $return_code);
+       }
+
+       /**
+        * Return the ActivityPub profile of the given user
+        *
+        * @param integer $uid User ID
+        * @return array
+        */
+       public static function profile($uid)
+       {
+               $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
+
+               $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
+                       'account_removed' => false, 'verified' => true];
+               $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
+               $user = DBA::selectFirst('user', $fields, $condition);
+               if (!DBA::isResult($user)) {
+                       return [];
+               }
+
+               $fields = ['locality', 'region', 'country-name'];
+               $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
+               if (!DBA::isResult($profile)) {
+                       return [];
+               }
+
+               $fields = ['name', 'url', 'location', 'about', 'avatar'];
+               $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
+               if (!DBA::isResult($contact)) {
+                       return [];
+               }
+
+               $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
+                       ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
+                       'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
+
+               $data['id'] = $contact['url'];
+               $data['uuid'] = $user['guid'];
+               $data['type'] = $accounttype[$user['account-type']];
+               $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
+               $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
+               $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
+               $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
+               $data['preferredUsername'] = $user['nickname'];
+               $data['name'] = $contact['name'];
+               $data['vcard:hasAddress'] = ['@type' => 'Home', 'vcard:country-name' => $profile['country-name'],
+                       'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
+               $data['summary'] = $contact['about'];
+               $data['url'] = $contact['url'];
+               $data['manuallyApprovesFollowers'] = false;
+               $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
+                       'owner' => $contact['url'],
+                       'publicKeyPem' => $user['pubkey']];
+               $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
+               $data['icon'] = ['type' => 'Image',
+                       'url' => $contact['avatar']];
+
+               // tags: https://kitty.town/@inmysocks/100656097926961126.json
+               return $data;
+       }
+
+       public static function createActivityFromItem($item_id)
+       {
+               $item = Item::selectFirst([], ['id' => $item_id]);
+
+               $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
+                       ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
+                       'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
+                       'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
+                       'toot' => 'http://joinmastodon.org/ns#']]];
+
+               $data['type'] = 'Create';
+               $data['id'] = $item['uri'];
+               $data['actor'] = $item['author-link'];
+               $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
+               $data['object'] = self::createNote($item);
+               return $data;
+       }
+
+       public static function createNote($item)
+       {
+               $data = [];
+               $data['type'] = 'Note';
+               $data['id'] = $item['uri'];
+
+               if ($item['uri'] != $item['thr-parent']) {
+                       $data['inReplyTo'] = $item['thr-parent'];
+               }
+
+               $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
+               if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
+                       $conversation_uri = $conversation['conversation-uri'];
+               } else {
+                       $conversation_uri = $item['parent-uri'];
+               }
+
+               $data['context'] = $data['conversation'] = $conversation_uri;
+               $data['actor'] = $item['author-link'];
+               $data['to'] = [];
+               if (!$item['private']) {
+                       $data['to'][] = 'https://www.w3.org/ns/activitystreams#Public';
+               }
+               $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
+               $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
+               $data['attributedTo'] = $item['author-link'];
+               $data['name'] = BBCode::convert($item['title'], false, 7);
+               $data['content'] = BBCode::convert($item['body'], false, 7);
+               $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
+               //$data['summary'] = ''; // Ignore by now
+               //$data['sensitive'] = false; // - Query NSFW
+               //$data['emoji'] = []; // Ignore by now
+               //$data['tag'] = []; /// @ToDo
+               //$data['attachment'] = []; // @ToDo
+               return $data;
+       }
+
+       public static function transmitActivity($activity, $target, $uid)
+       {
+               $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
+
+               $owner = User::getOwnerDataById($uid);
+
+               $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
+                       'id' => System::baseUrl() . '/activity/' . System::createGUID(),
+                       'type' => $activity,
+                       'actor' => $owner['url'],
+                       'object' => $profile['url']];
+
+               logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
+               return self::transmit($data,  $profile['notify'], $uid);
+       }
+
+       public static function transmitContactAccept($target, $id, $uid)
+       {
+               $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
+
+               $owner = User::getOwnerDataById($uid);
+               $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
+                       'id' => System::baseUrl() . '/activity/' . System::createGUID(),
+                       'type' => 'Accept',
+                       'actor' => $owner['url'],
+                       'object' => ['id' => $id, 'type' => 'Follow',
+                               'actor' => $profile['url'],
+                               'object' => $owner['url']]];
+
+               logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
+               return self::transmit($data,  $profile['notify'], $uid);
+       }
+
+       public static function transmitContactUndo($target, $id, $uid)
+       {
+               $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
+
+               if (empty($id)) {
+                       $id = System::baseUrl() . '/activity/' . System::createGUID();
+               }
+
+               $owner = User::getOwnerDataById($uid);
+               $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
+                       'id' => System::baseUrl() . '/activity/' . System::createGUID(),
+                       'type' => 'Undo',
+                       'actor' => $owner['url'],
+                       'object' => ['id' => $id, 'type' => 'Follow',
+                               'actor' => $owner['url'],
+                               'object' => $profile['url']]];
+
+               logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
+               return self::transmit($data,  $profile['notify'], $uid);
+       }
+
+       /**
+        * Fetches ActivityPub content from the given url
+        *
+        * @param string $url content url
+        * @return array
+        */
+       public static function fetchContent($url)
+       {
+               $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json']);
+
+               if (!$ret['success'] || empty($ret['body'])) {
+                       return;
+               }
+
+               return json_decode($ret['body'], true);
+       }
+
+       /**
+        * Resolves the profile url from the address by using webfinger
+        *
+        * @param string $addr profile address (user@domain.tld)
+        * @return string url
+        */
+       private static function addrToUrl($addr)
+       {
+               $addr_parts = explode('@', $addr);
+               if (count($addr_parts) != 2) {
+                       return false;
+               }
+
+               $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
+
+               $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
+               if (!$ret['success'] || empty($ret['body'])) {
+                       return false;
+               }
+
+               $data = json_decode($ret['body'], true);
+
+               if (empty($data['links'])) {
+                       return false;
+               }
+
+               foreach ($data['links'] as $link) {
+                       if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
+                               continue;
+                       }
+
+                       if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
+                               return $link['href'];
+                       }
+               }
+
+               return false;
+       }
+
+       public static function verifySignature($content, $http_headers)
+       {
+               $object = json_decode($content, true);
+
+               if (empty($object)) {
+                       return false;
+               }
+
+               $actor = self::processElement($object, 'actor', 'id');
+
+               $headers = [];
+               $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
+
+               // First take every header
+               foreach ($http_headers as $k => $v) {
+                       $field = str_replace('_', '-', strtolower($k));
+                       $headers[$field] = $v;
+               }
+
+               // Now add every http header
+               foreach ($http_headers as $k => $v) {
+                       if (strpos($k, 'HTTP_') === 0) {
+                               $field = str_replace('_', '-', strtolower(substr($k, 5)));
+                               $headers[$field] = $v;
+                       }
+               }
+
+               $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
+
+               if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
+                       return false;
+               }
+
+               $signed_data = '';
+               foreach ($sig_block['headers'] as $h) {
+                       if (array_key_exists($h, $headers)) {
+                               $signed_data .= $h . ': ' . $headers[$h] . "\n";
+                       }
+               }
+               $signed_data = rtrim($signed_data, "\n");
+
+               if (empty($signed_data)) {
+                       return false;
+               }
+
+               $algorithm = null;
+
+               if ($sig_block['algorithm'] === 'rsa-sha256') {
+                       $algorithm = 'sha256';
+               }
+
+               if ($sig_block['algorithm'] === 'rsa-sha512') {
+                       $algorithm = 'sha512';
+               }
+
+               if (empty($algorithm)) {
+                       return false;
+               }
+
+               $key = self::fetchKey($sig_block['keyId'], $actor);
+
+               if (empty($key)) {
+                       return false;
+               }
+
+               if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
+                       return false;
+               }
+
+               // Check the digest if it was part of the signed data
+               if (in_array('digest', $sig_block['headers'])) {
+                       $digest = explode('=', $headers['digest'], 2);
+                       if ($digest[0] === 'SHA-256') {
+                               $hashalg = 'sha256';
+                       }
+                       if ($digest[0] === 'SHA-512') {
+                               $hashalg = 'sha512';
+                       }
+
+                       /// @todo add all hashes from the rfc
+
+                       if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
+                               return false;
+                       }
+               }
+
+               // Check the content-length if it was part of the signed data
+               if (in_array('content-length', $sig_block['headers'])) {
+                       if (strlen($content) != $headers['content-length']) {
+                               return false;
+                       }
+               }
+
+               return true;
+
+       }
+
+       private static function fetchKey($id, $actor)
+       {
+               $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
+
+               $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
+               if (!empty($profile)) {
+                       return $profile['pubkey'];
+               } elseif ($url != $actor) {
+                       $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
+                       if (!empty($profile)) {
+                               return $profile['pubkey'];
+                       }
+               }
+
+               return false;
+       }
+
+       /**
+        * @brief
+        *
+        * @param string $header
+        * @return array associate array with
+        *   - \e string \b keyID
+        *   - \e string \b algorithm
+        *   - \e array  \b headers
+        *   - \e string \b signature
+        */
+       private static function parseSigHeader($header)
+       {
+               $ret = [];
+               $matches = [];
+
+               if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
+                       $ret['keyId'] = $matches[1];
+               }
+
+               if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
+                       $ret['algorithm'] = $matches[1];
+               }
+
+               if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
+                       $ret['headers'] = explode(' ', $matches[1]);
+               }
+
+               if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
+                       $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
+               }
+
+               return $ret;
+       }
+
+       /**
+        * Fetches a profile from the given url
+        *
+        * @param string $url profile url
+        * @return array
+        */
+       public static function fetchProfile($url)
+       {
+               if (empty(parse_url($url, PHP_URL_SCHEME))) {
+                       $url = self::addrToUrl($url);
+                       if (empty($url)) {
+                               return false;
+                       }
+               }
+
+               $data = self::fetchContent($url);
+
+               if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
+                       return false;
+               }
+
+               $profile = ['network' => Protocol::ACTIVITYPUB];
+               $profile['nick'] = $data['preferredUsername'];
+               $profile['name'] = defaults($data, 'name', $profile['nick']);
+               $profile['guid'] = defaults($data, 'uuid', null);
+               $profile['url'] = $data['id'];
+
+               $parts = parse_url($profile['url']);
+               unset($parts['scheme']);
+               unset($parts['path']);
+               $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
+               $profile['alias'] = self::processElement($data, 'url', 'href');
+               $profile['photo'] = self::processElement($data, 'icon', 'url');
+               // $profile['community']
+               // $profile['keywords']
+               // $profile['location']
+               $profile['about'] = defaults($data, 'summary', '');
+               $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
+               $profile['notify'] = $data['inbox'];
+               $profile['poll'] = $data['outbox'];
+               $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
+
+               // Check if the address is resolvable
+               if (self::addrToUrl($profile['addr']) == $profile['url']) {
+                       $parts = parse_url($profile['url']);
+                       unset($parts['path']);
+                       $profile['baseurl'] = Network::unparseURL($parts);
+               } else {
+                       unset($profile['addr']);
+               }
+
+               if ($profile['url'] == $profile['alias']) {
+                       unset($profile['alias']);
+               }
+
+               // Remove all "null" fields
+               foreach ($profile as $field => $content) {
+                       if (is_null($content)) {
+                               unset($profile[$field]);
+                       }
+               }
+
+/*
+               // To-Do
+               unset($data['type']);
+               unset($data['manuallyApprovesFollowers']);
+
+               // Unhandled
+               unset($data['@context']);
+               unset($data['tag']);
+               unset($data['attachment']);
+               unset($data['image']);
+               unset($data['nomadicLocations']);
+               unset($data['signature']);
+               unset($data['following']);
+               unset($data['followers']);
+               unset($data['featured']);
+               unset($data['movedTo']);
+               unset($data['liked']);
+               unset($data['sharedInbox']); // Misskey
+               unset($data['isCat']); // Misskey
+               unset($data['kroeg:blocks']); // Kroeg
+               unset($data['updated']); // Kroeg
+*/
+               return $profile;
+       }
+
+       public static function processInbox($body, $header, $uid)
+       {
+               logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
+
+               if (!self::verifySignature($body, $header)) {
+                       logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
+                       return;
+               }
+
+               $activity = json_decode($body, true);
+
+               if (!is_array($activity)) {
+                       logger('Invalid body.', LOGGER_DEBUG);
+                       return;
+               }
+
+               self::processActivity($activity, $body, $uid);
+       }
+
+       public static function fetchOutbox($url)
+       {
+               $data = self::fetchContent($url);
+               if (empty($data)) {
+                       return;
+               }
+
+               if (!empty($data['orderedItems'])) {
+                       $items = $data['orderedItems'];
+               } elseif (!empty($data['first']['orderedItems'])) {
+                       $items = $data['first']['orderedItems'];
+               } elseif (!empty($data['first'])) {
+                       self::fetchOutbox($data['first']);
+                       return;
+               } else {
+                       $items = [];
+               }
+
+               foreach ($items as $activity) {
+                       self::processActivity($activity);
+               }
+       }
+
+       function processActivity($activity, $body = '', $uid = null)
+       {
+               if (empty($activity['type'])) {
+                       logger('Empty type', LOGGER_DEBUG);
+                       return;
+               }
+
+               if (empty($activity['object'])) {
+                       logger('Empty object', LOGGER_DEBUG);
+                       return;
+               }
+
+               if (empty($activity['actor'])) {
+                       logger('Empty actor', LOGGER_DEBUG);
+                       return;
+
+               }
+
+               $actor = self::processElement($activity, 'actor', 'id');
+               if (empty($actor)) {
+                       logger('Empty actor - 2', LOGGER_DEBUG);
+                       return;
+               }
+
+               if (is_string($activity['object'])) {
+                       $object_url = $activity['object'];
+               } elseif (!empty($activity['object']['id'])) {
+                       $object_url = $activity['object']['id'];
+               } else {
+                       logger('No object found', LOGGER_DEBUG);
+                       return;
+               }
+
+               // ----------------------------------
+/*
+               // unhandled
+               unset($activity['@context']);
+               unset($activity['id']);
+
+               // Non standard
+               unset($activity['title']);
+               unset($activity['atomUri']);
+               unset($activity['context_id']);
+               unset($activity['statusnetConversationId']);
+
+               // To-Do?
+               unset($activity['context']);
+               unset($activity['location']);
+               unset($activity['signature']);
+*/
+               // Fetch all receivers from to, cc, bto and bcc
+               $receivers = self::getReceivers($activity);
+
+               // When it is a delivery to a personal inbox we add that user to the receivers
+               if (!empty($uid)) {
+                       $owner = User::getOwnerDataById($uid);
+                       $additional = [$owner['url'] => $uid];
+                       $receivers = array_merge($receivers, $additional);
+               }
+
+               logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
+
+               logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
+
+               // Fetch the content only on activities where this matters
+               if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
+                       $item = self::fetchObject($object_url, $activity['object']);
+                       if (empty($item)) {
+                               logger("Object data couldn't be processed", LOGGER_DEBUG);
+                               return;
+                       }
+               } else {
+                       if (in_array($activity['type'], ['Accept'])) {
+                               $item['object'] = self::processElement($activity, 'object', 'actor', 'type', 'Follow');
+                       } elseif (in_array($activity['type'], ['Undo'])) {
+                               $item['object'] = self::processElement($activity, 'object', 'object', 'type', 'Follow');
+                       } else {
+                               $item['object'] = $object_url;
+                       }
+                       $item['id'] = $activity['id'];
+                       $item['receiver'] = [];
+                       $item['type'] = $activity['type'];
+               }
+
+               $item = self::addActivityFields($item, $activity);
+
+               $item['owner'] = $actor;
+
+               $item['receiver'] = array_merge($item['receiver'], $receivers);
+
+               switch ($activity['type']) {
+                       case 'Create':
+                       case 'Update':
+                       case 'Announce':
+                               self::createItem($item, $body);
+                               break;
+
+                       case 'Like':
+                               self::likeItem($item, $body);
+                               break;
+
+                       case 'Dislike':
+                               break;
+
+                       case 'Delete':
+                               break;
+
+                       case 'Follow':
+                               self::followUser($item);
+                               break;
+
+                       case 'Accept':
+                               self::acceptFollowUser($item);
+                               break;
+
+                       case 'Undo':
+                               self::undoFollowUser($item);
+                               break;
+
+                       default:
+                               logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
+                               break;
+               }
+       }
+
+       private static function getReceivers($activity)
+       {
+               $receivers = [];
+
+               $elements = ['to', 'cc', 'bto', 'bcc'];
+               foreach ($elements as $element) {
+                       if (empty($activity[$element])) {
+                               continue;
+                       }
+
+                       // The receiver can be an arror or a string
+                       if (is_string($activity[$element])) {
+                               $activity[$element] = [$activity[$element]];
+                       }
+
+                       foreach ($activity[$element] as $receiver) {
+                               if ($receiver == self::PUBLIC) {
+                                       $receivers[$receiver] = 0;
+                               }
+
+                               $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
+                               $contact = DBA::selectFirst('contact', ['uid'], $condition);
+                               if (!DBA::isResult($contact)) {
+                                       continue;
+                               }
+                               $receivers[$receiver] = $contact['uid'];
+                       }
+               }
+               return $receivers;
+       }
+
+       private static function addActivityFields($item, $activity)
+       {
+               if (!empty($activity['published']) && empty($item['published'])) {
+                       $item['published'] = $activity['published'];
+               }
+
+               if (!empty($activity['updated']) && empty($item['updated'])) {
+                       $item['updated'] = $activity['updated'];
+               }
+
+               if (!empty($activity['inReplyTo']) && empty($item['parent-uri'])) {
+                       $item['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
+               }
+
+               if (!empty($activity['instrument'])) {
+                       $item['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
+               }
+               return $item;
+       }
+
+       private static function fetchObject($object_url, $object = [])
+       {
+               $data = self::fetchContent($object_url);
+               if (empty($data)) {
+                       $data = $object;
+                       if (empty($data)) {
+                               logger('Empty content', LOGGER_DEBUG);
+                               return false;
+                       } elseif (is_string($data)) {
+                               logger('No object array provided.', LOGGER_DEBUG);
+                               $item = Item::selectFirst([], ['uri' => $data]);
+                               if (!DBA::isResult($item)) {
+                                       logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
+                                       return false;
+                               }
+                               logger('Using already stored item', LOGGER_DEBUG);
+                               $data = self::createNote($item);
+                       } else {
+                               logger('Using provided object', LOGGER_DEBUG);
+                       }
+               }
+
+               if (empty($data['type'])) {
+                       logger('Empty type', LOGGER_DEBUG);
+                       return false;
+               } else {
+                       $type = $data['type'];
+                       logger('Type ' . $type, LOGGER_DEBUG);
+               }
+
+               if (in_array($type, ['Note', 'Article', 'Video'])) {
+                       $common = self::processCommonData($data);
+               }
+
+               switch ($type) {
+                       case 'Note':
+                               return array_merge($common, self::processNote($data));
+                       case 'Article':
+                               return array_merge($common, self::processArticle($data));
+                       case 'Video':
+                               return array_merge($common, self::processVideo($data));
+
+                       case 'Announce':
+                               if (empty($data['object'])) {
+                                       return false;
+                               }
+                               return self::fetchObject($data['object']);
+
+                       case 'Person':
+                       case 'Tombstone':
+                               break;
+
+                       default:
+                               logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
+                               break;
+               }
+       }
+
+       private static function processCommonData(&$object)
+       {
+               if (empty($object['id']) || empty($object['attributedTo'])) {
+                       return false;
+               }
+
+               $item = [];
+               $item['type'] = $object['type'];
+               $item['uri'] = $object['id'];
+
+               if (!empty($object['inReplyTo'])) {
+                       $item['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
+               } else {
+                       $item['reply-to-uri'] = $item['uri'];
+               }
+
+               $item['published'] = defaults($object, 'published', null);
+               $item['updated'] = defaults($object, 'updated', $item['published']);
+
+               if (empty($item['published']) && !empty($item['updated'])) {
+                       $item['published'] = $item['updated'];
+               }
+
+               $item['uuid'] = defaults($object, 'uuid', null);
+               $item['owner'] = $item['author'] = self::processElement($object, 'attributedTo', 'id');
+               $item['context'] = defaults($object, 'context', null);
+               $item['conversation'] = defaults($object, 'conversation', null);
+               $item['sensitive'] = defaults($object, 'sensitive', null);
+               $item['name'] = defaults($object, 'title', null);
+               $item['name'] = defaults($object, 'name', $item['name']);
+               $item['summary'] = defaults($object, 'summary', null);
+               $item['content'] = defaults($object, 'content', null);
+               $item['source'] = defaults($object, 'source', null);
+               $item['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
+               $item['attachments'] = defaults($object, 'attachment', null);
+               $item['tags'] = defaults($object, 'tag', null);
+               $item['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
+               $item['alternate-url'] = self::processElement($object, 'url', 'href');
+               $item['receiver'] = self::getReceivers($object);
+
+/*
+               // To-Do
+               unset($object['source']);
+
+               // Unhandled
+               unset($object['@context']);
+               unset($object['type']);
+               unset($object['actor']);
+               unset($object['signature']);
+               unset($object['mediaType']);
+               unset($object['duration']);
+               unset($object['replies']);
+               unset($object['icon']);
+
+               // Also missing:
+               audience, preview, endTime, startTime, generator, image
+*/
+               return $item;
+       }
+
+       private static function processNote($object)
+       {
+               $item = [];
+
+/*
+               // To-Do?
+               unset($object['emoji']);
+               unset($object['atomUri']);
+               unset($object['inReplyToAtomUri']);
+
+               // Unhandled
+               unset($object['contentMap']);
+               unset($object['announcement_count']);
+               unset($object['announcements']);
+               unset($object['context_id']);
+               unset($object['likes']);
+               unset($object['like_count']);
+               unset($object['inReplyToStatusId']);
+               unset($object['shares']);
+               unset($object['quoteUrl']);
+               unset($object['statusnetConversationId']);
+*/
+               return $item;
+       }
+
+       private static function processArticle($object)
+       {
+               $item = [];
+
+               return $item;
+       }
+
+       private static function processVideo($object)
+       {
+               $item = [];
+/*
+               // To-Do?
+               unset($object['category']);
+               unset($object['licence']);
+               unset($object['language']);
+               unset($object['commentsEnabled']);
+
+               // Unhandled
+               unset($object['views']);
+               unset($object['waitTranscoding']);
+               unset($object['state']);
+               unset($object['support']);
+               unset($object['subtitleLanguage']);
+               unset($object['likes']);
+               unset($object['dislikes']);
+               unset($object['shares']);
+               unset($object['comments']);
+*/
+               return $item;
+       }
+
+       private static function processElement($array, $element, $key, $type = null, $type_value = null)
+       {
+               if (empty($array)) {
+                       return false;
+               }
+
+               if (empty($array[$element])) {
+                       return false;
+               }
+
+               if (is_string($array[$element])) {
+                       return $array[$element];
+               }
+
+               if (is_null($type_value)) {
+                       if (!empty($array[$element][$key])) {
+                               return $array[$element][$key];
+                       }
+
+                       if (!empty($array[$element][0][$key])) {
+                               return $array[$element][0][$key];
+                       }
+
+                       return false;
+               }
+
+               if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
+                       return $array[$element][$key];
+               }
+
+               /// @todo Add array search
+
+               return false;
+       }
+
+       private static function convertMentions($body)
+       {
+               $URLSearchString = "^\[\]";
+               $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
+
+               return $body;
+       }
+
+       private static function constructTagList($tags, $sensitive)
+       {
+               if (empty($tags)) {
+                       return '';
+               }
+
+               $tag_text = '';
+               foreach ($tags as $tag) {
+                       if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
+                               if (!empty($tag_text)) {
+                                       $tag_text .= ',';
+                               }
+
+                               $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
+                       }
+               }
+
+               /// @todo add nsfw for $sensitive
+
+               return $tag_text;
+       }
+
+       private static function constructAttachList($attachments, $item)
+       {
+               if (empty($attachments)) {
+                       return $item;
+               }
+
+               foreach ($attachments as $attach) {
+                       $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
+                       if ($filetype == 'image') {
+                               $item['body'] .= "\n[img]".$attach['url'].'[/img]';
+                       } else {
+                               if (!empty($item["attach"])) {
+                                       $item["attach"] .= ',';
+                               } else {
+                                       $item["attach"] = '';
+                               }
+                               if (!isset($attach['length'])) {
+                                       $attach['length'] = "0";
+                               }
+                               $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
+                       }
+               }
+
+               return $item;
+       }
+
+       private static function createItem($activity, $body)
+       {
+               $item = [];
+               $item['verb'] = ACTIVITY_POST;
+               $item['parent-uri'] = $activity['reply-to-uri'];
+
+               if ($activity['reply-to-uri'] == $activity['uri']) {
+                       $item['gravity'] = GRAVITY_PARENT;
+                       $item['object-type'] = ACTIVITY_OBJ_NOTE;
+               } else {
+                       $item['gravity'] = GRAVITY_COMMENT;
+                       $item['object-type'] = ACTIVITY_OBJ_COMMENT;
+               }
+
+               self::postItem($activity, $item, $body);
+       }
+
+       private static function likeItem($activity, $body)
+       {
+               $item = [];
+               $item['verb'] = ACTIVITY_LIKE;
+               $item['parent-uri'] = $activity['object'];
+               $item['gravity'] = GRAVITY_ACTIVITY;
+               $item['object-type'] = ACTIVITY_OBJ_NOTE;
+
+               self::postItem($activity, $item, $body);
+       }
+
+       private static function postItem($activity, $item, $body)
+       {
+               /// @todo What to do with $activity['context']?
+
+               $item['network'] = Protocol::ACTIVITYPUB;
+               $item['private'] = !in_array(0, $activity['receiver']);
+               $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
+               $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
+               $item['uri'] = $activity['uri'];
+               $item['created'] = $activity['published'];
+               $item['edited'] = $activity['updated'];
+               $item['guid'] = $activity['uuid'];
+               $item['title'] = HTML::toBBCode($activity['name']);
+               $item['content-warning'] = HTML::toBBCode($activity['summary']);
+               $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
+               $item['location'] = $activity['location'];
+               $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
+               $item['app'] = $activity['service'];
+               $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
+
+               $item = self::constructAttachList($activity['attachments'], $item);
+
+               $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
+               if (!empty($source)) {
+                       $item['body'] = $source;
+               }
+
+               $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
+               $item['source'] = $body;
+               $item['conversation-uri'] = $activity['conversation'];
+
+               foreach ($activity['receiver'] as $receiver) {
+                       $item['uid'] = $receiver;
+                       $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
+
+                       if (($receiver != 0) && empty($item['contact-id'])) {
+                               $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
+                       }
+
+                       $item_id = Item::insert($item);
+                       logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
+                       if (!empty($item_id) && ($item['uid'] == 0)) {
+                               Item::distribute($item_id);
+                       }
+               }
+       }
+
+       private static function followUser($activity)
+       {
+               if (empty($activity['receiver'][$activity['object']])) {
+                       return;
+               }
+
+               $uid = $activity['receiver'][$activity['object']];
+               $owner = User::getOwnerDataById($uid);
+
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (!empty($cid)) {
+                       $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
+               } else {
+                       $contact = false;
+               }
+
+               $item = ['author-id' => Contact::getIdForURL($activity['owner']),
+                       'author-link' => $activity['owner']];
+
+               Contact::addRelationship($owner, $contact, $item);
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (empty($cid)) {
+                       return;
+               }
+
+               $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
+               if ($contact['network'] != Protocol::ACTIVITYPUB) {
+                       Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
+               }
+
+               DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
+               logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
+       }
+
+       private static function acceptFollowUser($activity)
+       {
+               if (empty($activity['receiver'][$activity['object']])) {
+                       return;
+               }
+
+               $uid = $activity['receiver'][$activity['object']];
+               $owner = User::getOwnerDataById($uid);
+
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (empty($cid)) {
+                       logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
+                       return;
+               }
+
+               $fields = ['pending' => false];
+               $condition = ['id' => $cid, 'pending' => true];
+               DBA::update('comtact', $fields, $condition);
+               logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
+       }
+
+       private static function undoFollowUser($activity)
+       {
+               if (empty($activity['receiver'][$activity['object']])) {
+                       return;
+               }
+
+               $uid = $activity['receiver'][$activity['object']];
+               $owner = User::getOwnerDataById($uid);
+
+               $cid = Contact::getIdForURL($activity['owner'], $uid);
+               if (empty($cid)) {
+                       logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
+                       return;
+               }
+
+               $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
+               if (!DBA::isResult($contact)) {
+                       return;
+               }
+
+               Contact::removeFollower($owner, $contact);
+               logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
+       }
+}
index 27cfdccd853af83b89d026ddaf6fb5e741e25605..e7edcdc490a9363d693d502bec5d29df73006af1 100644 (file)
@@ -1592,17 +1592,13 @@ class Diaspora
                if (DBA::isResult($item)) {
                        return $item["uri"];
                } elseif (!$onlyfound) {
-                       $contact = Contact::getDetailsByAddr($author, 0);
-                       if (!empty($contact['network'])) {
-                               $prefix = 'urn:X-' . $contact['network'] . ':';
-                       } else {
-                               // This fallback should happen most unlikely
-                               $prefix = 'urn:X-dspr:';
-                       }
+                       $person = self::personByHandle($author);
 
-                       $author_parts = explode('@', $author);
+                       $parts = parse_url($person['url']);
+                       unset($parts['path']);
+                       $host_url = Network::unparseURL($parts);
 
-                       return $prefix . $author_parts[1] . ':' . $author_parts[0] . ':'. $guid;
+                       return $host_url . '/object/' . $guid;
                }
 
                return "";
index 2939f69e55c2cbe42727cd76e7b41952df811bda..280dbe72c2a2afe151b5c5d47dd8e11a561fc182 100644 (file)
@@ -333,7 +333,7 @@ class PortableContact
                        $server_url = normalise_link(self::detectServer($profile));
                }
 
-               if (!in_array($gcontacts[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
+               if (!in_array($gcontacts[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::FEED, Protocol::OSTATUS, ""])) {
                        logger("Profile ".$profile.": Network type ".$gcontacts[0]["network"]." can't be checked", LOGGER_DEBUG);
                        return false;
                }
index 61eaba388b2d365a58829bcf4abddcb1bda54874..55f80c94d77359dec401efbe75ec0be67b78e517 100644 (file)
@@ -363,9 +363,9 @@ class Notifier
                                }
 
                                // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
-                               $networks = [Protocol::OSTATUS, Protocol::DFRN];
+                               $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DFRN];
                        } else {
-                               $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
+                               $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
                        }
                } else {
                        $public_message = false;
index f2919e4a750e148e0e8531171d9b786e8a1dc3c5..67362917c379418ed2d98652e332e99b351ffd58 100644 (file)
@@ -29,13 +29,13 @@ class UpdateGContact
                        return;
                }
 
-               if (!in_array($r[0]["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
+               if (!in_array($r[0]["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
                        return;
                }
 
                $data = Probe::uri($r[0]["url"]);
 
-               if (!in_array($data["network"], [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
+               if (!in_array($data["network"], [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS])) {
                        if ($r[0]["server_url"] != "") {
                                PortableContact::checkServer($r[0]["server_url"], $r[0]["network"]);
                        }