]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/Diaspora.php
Merge branch 'friendica:develop' into bug-noLocalPosts
[friendica.git] / src / Protocol / Diaspora.php
index 66ace1d3db448dbb09cb496dc15d955fd41c2fb3..54f09e9d970c8ce209249a39a609b17d2c989b90 100644 (file)
@@ -54,7 +54,8 @@ use GuzzleHttp\Psr7\Uri;
 use SimpleXMLElement;
 
 /**
- * This class contain functions to create and send Diaspora XML files
+ * This class contains functions to communicate via the Diaspora protocol
+ * @see https://diaspora.github.io/diaspora_federation/
  */
 class Diaspora
 {
@@ -83,7 +84,7 @@ class Diaspora
                }
 
                $items = Post::select(['author-id', 'author-link', 'parent-author-link', 'parent-guid', 'guid'],
-                       ['parent' => $item['parent'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
+                       ['parent' => $item['parent'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
                while ($item = Post::fetch($items)) {
                        $contact = DBA::selectFirst('contact', ['id', 'url', 'name', 'protocol', 'batch', 'network'],
                                ['id' => $item['author-id']]);
@@ -223,14 +224,34 @@ class Diaspora
 
                // Is it a private post? Then decrypt the outer Salmon
                if (is_object($data)) {
-                       $encrypted_aes_key_bundle = base64_decode($data->aes_key);
-                       $ciphertext = base64_decode($data->encrypted_magic_envelope);
+                       try {
+                               if (!isset($data->aes_key) || !isset($data->encrypted_magic_envelope)) {
+                                       Logger::info('Missing keys "aes_key" and/or "encrypted_magic_envelope"', ['data' => $data]);
+                                       throw new \RuntimeException('Missing keys "aes_key" and/or "encrypted_magic_envelope"');
+                               }
 
-                       $outer_key_bundle = '';
-                       @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
-                       $j_outer_key_bundle = json_decode($outer_key_bundle);
+                               $encrypted_aes_key_bundle = base64_decode($data->aes_key);
+                               $ciphertext = base64_decode($data->encrypted_magic_envelope);
+
+                               $outer_key_bundle = '';
+                               @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $privKey);
+                               $j_outer_key_bundle = json_decode($outer_key_bundle);
+
+                               if (!is_object($j_outer_key_bundle)) {
+                                       Logger::info('Unable to decode outer key bundle', ['outer_key_bundle' => $outer_key_bundle]);
+                                       throw new \RuntimeException('Unable to decode outer key bundle');
+                               }
+
+                               if (!isset($j_outer_key_bundle->iv) || !isset($j_outer_key_bundle->key)) {
+                                       Logger::info('Missing keys "iv" and/or "key" from outer Salmon', ['j_outer_key_bundle' => $j_outer_key_bundle]);
+                                       throw new \RuntimeException('Missing keys "iv" and/or "key" from outer Salmon');
+                               }
+
+                               $outer_iv = base64_decode($j_outer_key_bundle->iv);
+                               $outer_key = base64_decode($j_outer_key_bundle->key);
 
-                       if (!is_object($j_outer_key_bundle)) {
+                               $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
+                       } catch (\Throwable $e) {
                                Logger::notice('Outer Salmon did not verify. Discarding.');
                                if ($no_exit) {
                                        return false;
@@ -238,11 +259,6 @@ class Diaspora
                                        throw new \Friendica\Network\HTTPException\BadRequestException();
                                }
                        }
-
-                       $outer_iv = base64_decode($j_outer_key_bundle->iv);
-                       $outer_key = base64_decode($j_outer_key_bundle->key);
-
-                       $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
                } else {
                        $xml = $raw;
                }
@@ -776,36 +792,6 @@ class Diaspora
                return '';
        }
 
-       /**
-        * get a handle (user@domain.tld) from a given contact id
-        *
-        * @param int $contact_id  The id in the contact table
-        * @param int $pcontact_id The id in the contact table (Used for the public contact)
-        *
-        * @return string the handle
-        * @throws \Exception
-        */
-       private static function handleFromContact(int $contact_id, int $pcontact_id = 0): string
-       {
-               $handle = '';
-
-               if ($pcontact_id != 0) {
-                       $contact = Contact::getById($pcontact_id, ['addr']);
-                       if (DBA::isResult($contact)) {
-                               $handle = $contact['addr'];
-                       }
-               }
-
-               if (empty($handle)) {
-                       $contact = Contact::getById($contact_id, ['addr']);
-                       if (DBA::isResult($contact)) {
-                               $handle = $contact['addr'];
-                       }
-               }
-
-               return strtolower($handle);
-       }
-
        /**
         * Get a contact id for a given handle
         *
@@ -1548,7 +1534,7 @@ class Diaspora
                $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
 
                $datarray['verb'] = Activity::POST;
-               $datarray['gravity'] = GRAVITY_COMMENT;
+               $datarray['gravity'] = Item::GRAVITY_COMMENT;
 
                $datarray['thr-parent'] = $thr_parent ?: $toplevel_parent_item['uri'];
 
@@ -1801,7 +1787,7 @@ class Diaspora
                $datarray['uri'] = self::getUriFromGuid($author, $guid);
 
                $datarray['verb'] = $verb;
-               $datarray['gravity'] = GRAVITY_ACTIVITY;
+               $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
                $datarray['thr-parent'] = $toplevel_parent_item['uri'];
 
                $datarray['object-type'] = Activity\ObjectType::NOTE;
@@ -1812,7 +1798,7 @@ class Diaspora
                $datarray['changed'] = $datarray['created'] = $datarray['edited'] = DateTimeFormat::utcNow();
 
                // like on comments have the comment as parent. So we need to fetch the toplevel parent
-               if ($toplevel_parent_item['gravity'] != GRAVITY_PARENT) {
+               if ($toplevel_parent_item['gravity'] != Item::GRAVITY_PARENT) {
                        $toplevel = Post::selectFirst(['origin'], ['id' => $toplevel_parent_item['parent']]);
                        $origin = $toplevel['origin'];
                } else {
@@ -1981,7 +1967,7 @@ class Diaspora
                $datarray['uri'] = self::getUriFromGuid($author, $guid);
 
                $datarray['verb'] = Activity::FOLLOW;
-               $datarray['gravity'] = GRAVITY_ACTIVITY;
+               $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
                $datarray['thr-parent'] = $toplevel_parent_item['uri'];
 
                $datarray['object-type'] = Activity\ObjectType::NOTE;
@@ -2002,9 +1988,9 @@ class Diaspora
 
                // Send all existing comments and likes to the requesting server
                $comments = Post::select(['id', 'uri-id', 'parent-author-network', 'author-network', 'verb', 'gravity'],
-                       ['parent' => $toplevel_parent_item['id'], 'gravity' => [GRAVITY_COMMENT, GRAVITY_ACTIVITY]]);
+                       ['parent' => $toplevel_parent_item['id'], 'gravity' => [Item::GRAVITY_COMMENT, Item::GRAVITY_ACTIVITY]]);
                while ($comment = Post::fetch($comments)) {
-                       if (($comment['gravity'] == GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
+                       if (($comment['gravity'] == Item::GRAVITY_ACTIVITY) && !in_array($comment['verb'], [Activity::LIKE, Activity::DISLIKE])) {
                                Logger::info('Unsupported activities are not relayed', ['item' => $comment['id'], 'verb' => $comment['verb']]);
                                continue;
                        }
@@ -2020,7 +2006,7 @@ class Diaspora
                        }
 
                        Logger::info('Deliver participation', ['item' => $comment['id'], 'contact' => $author_contact['cid']]);
-                       if (Worker::add(PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
+                       if (Worker::add(Worker::PRIORITY_HIGH, 'Delivery', Delivery::POST, $comment['uri-id'], $author_contact['cid'], $datarray['uid'])) {
                                Post\DeliveryData::incrementQueueCount($comment['uri-id'], 1);
                        }
                }
@@ -2302,7 +2288,7 @@ class Diaspora
                $datarray['thr-parent'] = $parent['uri'];
 
                $datarray['verb'] = $datarray['body'] = Activity::ANNOUNCE;
-               $datarray['gravity'] = GRAVITY_ACTIVITY;
+               $datarray['gravity'] = Item::GRAVITY_ACTIVITY;
                $datarray['object-type'] = Activity\ObjectType::NOTE;
 
                $datarray['protocol'] = $item['protocol'];
@@ -2387,20 +2373,20 @@ class Diaspora
                $datarray['uri-id'] = ItemURI::insert(['uri' => $datarray['uri'], 'guid' => $datarray['guid']]);
 
                $datarray['verb'] = Activity::POST;
-               $datarray['gravity'] = GRAVITY_PARENT;
+               $datarray['gravity'] = Item::GRAVITY_PARENT;
 
                $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
                $datarray['source'] = $xml;
 
                $datarray = self::setDirection($datarray, $direction);
 
-               $datarray['body'] = DI::contentItem()->createSharedPostByGuid($root_guid, $importer['uid'], $original_person['url']);
-               $datarray['body'] = Diaspora::replacePeopleGuid($datarray['body'], $datarray['author-link']);
-
-               /// @todo Copy tag data from original post
-               Tag::storeFromBody($datarray['uri-id'], $datarray['body']);
+               $datarray['quote-uri-id'] = self::getQuoteUriId($root_guid, $importer['uid'], $original_person['url']);
+               if (empty($datarray['quote-uri-id'])) {
+                       return false;
+               }
 
-               $datarray['plink'] = self::plink($author, $guid);
+               $datarray['body']    = '';
+               $datarray['plink']   = self::plink($author, $guid);
                $datarray['private'] = (($public == 'false') ? Item::PRIVATE : Item::PUBLIC);
                $datarray['changed'] = $datarray['created'] = $datarray['edited'] = $created_at;
 
@@ -2431,6 +2417,25 @@ class Diaspora
                }
        }
 
+       private static function getQuoteUriId(string $guid, int $uid, string $host): int
+       {
+               $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
+
+               if (!DBA::isResult($shared_item) && !empty($host) && Diaspora::storeByGuid($guid, $host, true)) {
+                       Logger::debug('Fetched post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
+                       $shared_item = Post::selectFirst(['uri-id'], ['guid' => $guid, 'uid' => [$uid, 0], 'private' => [Item::PUBLIC, Item::UNLISTED]]);
+               } elseif (DBA::isResult($shared_item)) {
+                       Logger::debug('Found existing post', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
+               }
+
+               if (!DBA::isResult($shared_item)) {
+                       Logger::notice('Post does not exist.', ['guid' => $guid, 'host' => $host, 'uid' => $uid]);
+                       return 0;
+               }
+
+               return $shared_item['uri-id'];
+       }
+
        /**
         * Processes retractions
         *
@@ -2706,7 +2711,7 @@ class Diaspora
                $datarray['owner-id'] = $datarray['author-id'];
 
                $datarray['verb'] = Activity::POST;
-               $datarray['gravity'] = GRAVITY_PARENT;
+               $datarray['gravity'] = Item::GRAVITY_PARENT;
 
                $datarray['protocol'] = Conversation::PARCEL_DIASPORA;
                $datarray['source'] = $xml;
@@ -3201,61 +3206,30 @@ class Diaspora
        }
 
        /**
-        * Checks a message body if it is a reshare
+        * Fetch reshare details
         *
-        * @param string $body     The message body that is to be check
-        * @param bool   $complete Should it be a complete check or a simple check?
+        * @param array $item The message body that is to be check
         *
-        * @return array|bool Reshare details or "false" if no reshare
+        * @return array Reshare details (empty if the item is no reshare)
         * @throws \Friendica\Network\HTTPException\InternalServerErrorException
         * @throws \ImagickException
         */
-       public static function isReshare(string $body, bool $complete = true)
+       public static function getReshareDetails(array $item): array
        {
-               $body = trim($body);
-
-               $reshared = Item::getShareArray(['body' => $body]);
+               $reshared = DI::contentItem()->getSharedPost($item, ['guid', 'network', 'author-addr']);
                if (empty($reshared)) {
-                       return false;
-               }
-
-               // Skip if it isn't a pure repeated messages
-               // Does it start with a share?
-               if (!empty($reshared['comment']) && $complete) {
-                       return false;
-               }
-
-               if (!empty($reshared['guid']) && $complete) {
-                       $condition = ['guid' => $reshared['guid'], 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
-                       $item = Post::selectFirst(['contact-id'], $condition);
-                       if (DBA::isResult($item)) {
-                               $ret = [];
-                               $ret['root_handle'] = self::handleFromContact($item['contact-id']);
-                               $ret['root_guid'] = $reshared['guid'];
-                               return $ret;
-                       } elseif ($complete) {
-                               // We are resharing something that isn't a DFRN or Diaspora post.
-                               // So we have to return "false" on "$complete" to not trigger a reshare.
-                               return false;
-                       }
-               } elseif (empty($reshared['guid']) && $complete) {
-                       return false;
-               }
-
-               $ret = [];
-
-               if (!empty($reshared['profile']) && ($cid = Contact::getIdForURL($reshared['profile']))) {
-                       $contact = DBA::selectFirst('contact', ['addr'], ['id' => $cid]);
-                       if (!empty($contact['addr'])) {
-                               $ret['root_handle'] = $contact['addr'];
-                       }
+                       return [];
                }
 
-               if (empty($ret) && !$complete) {
-                       return true;
+               // Skip if it isn't a pure repeated messages or not a real reshare
+               if (!empty($reshared['comment']) || !in_array($reshared['post']['network'], [Protocol::DFRN, Protocol::DIASPORA])) {
+                       return [];
                }
 
-               return $ret;
+               return [
+                       'root_handle' => strtolower($reshared['post']['author-addr']),
+                       'root_guid'   => $reshared['post']['guid'],
+               ];
        }
 
        /**
@@ -3352,7 +3326,7 @@ class Diaspora
                $edited = DateTimeFormat::utc($item['edited'] ?? $item['created'], DateTimeFormat::ATOM);
 
                // Detect a share element and do a reshare
-               if (($item['private'] != Item::PRIVATE) && ($ret = self::isReshare($item['body']))) {
+               if (($item['private'] != Item::PRIVATE) && ($ret = self::getReshareDetails($item))) {
                        $message = [
                                'author'                => $myaddr,
                                'guid'                  => $item['guid'],
@@ -3366,7 +3340,7 @@ class Diaspora
                        $type = 'reshare';
                } else {
                        $title = $item['title'];
-                       $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
+                       $body  = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
 
                        // Fetch the title from an attached link - if there is one
                        if (empty($item['title']) && DI::pConfig()->get($owner['uid'], 'system', 'attach_link_title')) {
@@ -3376,11 +3350,6 @@ class Diaspora
                                }
                        }
 
-                       // @todo Check if this is obsolete and if we are still using different owners. (Possibly a fragment from the forum functionality)
-                       if ($item['author-link'] != $item['owner-link']) {
-                               $body = DI::contentItem()->createSharedBlockByArray($item);
-                       }
-
                        // convert to markdown
                        $body = html_entity_decode(BBCode::toMarkdown($body));
 
@@ -3588,7 +3557,7 @@ class Diaspora
                        $thread_parent_item = Post::selectFirst(['guid', 'author-id', 'author-link', 'gravity'], ['uri' => $item['thr-parent'], 'uid' => $item['uid']]);
                }
 
-               $body = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
+               $body = Post\Media::addAttachmentsToBody($item['uri-id'], DI::contentItem()->addSharedPost($item));
 
                // The replied to autor mention is prepended for clarity if:
                // - Item replied isn't yours
@@ -3596,7 +3565,7 @@ class Diaspora
                // - Implicit mentions are enabled
                if (
                        $item['author-id'] != $thread_parent_item['author-id']
-                       && ($thread_parent_item['gravity'] != GRAVITY_PARENT)
+                       && ($thread_parent_item['gravity'] != Item::GRAVITY_PARENT)
                        && (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions'))
                        && !DI::config()->get('system', 'disable_implicit_mentions')
                ) {
@@ -3684,7 +3653,7 @@ class Diaspora
 
                Logger::info('Got relayable data ' . $type . ' for item ' . $item['guid'] . ' (' . $item['id'] . ')');
 
-               $msg = json_decode($item['signed_text'], true);
+               $msg = json_decode($item['signed_text'] ?? '', true);
 
                $message = [];
                if (is_array($msg)) {
@@ -3725,11 +3694,11 @@ class Diaspora
         */
        public static function sendRetraction(array $item, array $owner, array $contact, bool $public_batch = false, bool $relay = false): int
        {
-               $itemaddr = self::handleFromContact($item['contact-id'], $item['author-id']);
+               $itemaddr = strtolower($item['author-addr']);
 
                $msg_type = 'retraction';
 
-               if ($item['gravity'] == GRAVITY_PARENT) {
+               if ($item['gravity'] == Item::GRAVITY_PARENT) {
                        $target_type = 'Post';
                } elseif (in_array($item['verb'], [Activity::LIKE, Activity::DISLIKE])) {
                        $target_type = 'Like';
@@ -4069,12 +4038,12 @@ class Diaspora
                        return false;
                }
 
-               if (($parent_post['gravity'] == GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
+               if (($parent_post['gravity'] == Item::GRAVITY_COMMENT) && empty($parent_post['signed_text'])) {
                        Logger::info('Parent comment has got no Diaspora signature.', ['parent-id' => $parent_id]);
                        return false;
                }
 
-               if ($parent_post['gravity'] == GRAVITY_COMMENT) {
+               if ($parent_post['gravity'] == Item::GRAVITY_COMMENT) {
                        return self::parentSupportDiaspora($parent_post['thr-parent-id']);
                }
 
@@ -4083,25 +4052,21 @@ class Diaspora
 
        public static function performReshare(int $UriId, int $uid): int
        {
-               $post = DI::contentItem()->createSharedPostByUriId($UriId, $uid);
-               if (empty($post)) {
-                       return 0;
-               }
-
                $owner  = User::getOwnerDataById($uid);
                $author = Contact::getPublicIdByUserId($uid);
 
                $item = [
-                       'uid'        => $uid,
-                       'verb'       => Activity::POST,
-                       'contact-id' => $owner['id'],
-                       'author-id'  => $author,
-                       'owner-id'   => $author,
-                       'body'       => $post,
-                       'allow_cid'  => $owner['allow_cid'] ?? '',
-                       'allow_gid'  => $owner['allow_gid']?? '',
-                       'deny_cid'   => $owner['deny_cid'] ?? '',
-                       'deny_gid'   => $owner['deny_gid'] ?? '',
+                       'uid'          => $uid,
+                       'verb'         => Activity::POST,
+                       'contact-id'   => $owner['id'],
+                       'author-id'    => $author,
+                       'owner-id'     => $author,
+                       'body'         => '',
+                       'quote-uri-id' => $UriId,
+                       'allow_cid'    => $owner['allow_cid'] ?? '',
+                       'allow_gid'    => $owner['allow_gid']?? '',
+                       'deny_cid'     => $owner['deny_cid'] ?? '',
+                       'deny_gid'     => $owner['deny_gid'] ?? '',
                ];
 
                if (!empty($item['allow_cid'] . $item['allow_gid'] . $item['deny_cid'] . $item['deny_gid'])) {