]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/ActivityPub/Transmitter.php
Merge pull request #8696 from MrPetovan/bug/8694-event-network-unkn
[friendica.git] / src / Protocol / ActivityPub / Transmitter.php
index dbfd67cb0dc2474b868a4a7f878ccb995009f35c..9cb5efca413038ce9aef3538a5aae04a019be66c 100644 (file)
@@ -1,14 +1,30 @@
 <?php
 /**
- * @file src/Protocol/ActivityPub/Transmitter.php
+ * @copyright Copyright (C) 2020, Friendica
+ *
+ * @license GNU AGPL version 3 or any later version
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program.  If not, see <https://www.gnu.org/licenses/>.
+ *
  */
+
 namespace Friendica\Protocol\ActivityPub;
 
 use Friendica\Content\Feature;
 use Friendica\Content\Text\BBCode;
 use Friendica\Content\Text\Plaintext;
-use Friendica\Core\Cache\Cache;
-use Friendica\Core\Config;
+use Friendica\Core\Cache\Duration;
 use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
 use Friendica\Core\System;
@@ -18,9 +34,10 @@ use Friendica\Model\APContact;
 use Friendica\Model\Contact;
 use Friendica\Model\Conversation;
 use Friendica\Model\Item;
+use Friendica\Model\ItemURI;
 use Friendica\Model\Profile;
 use Friendica\Model\Photo;
-use Friendica\Model\Term;
+use Friendica\Model\Tag;
 use Friendica\Model\User;
 use Friendica\Protocol\Activity;
 use Friendica\Protocol\ActivityPub;
@@ -37,81 +54,50 @@ require_once 'include/api.php';
 require_once 'mod/share.php';
 
 /**
- * @brief ActivityPub Transmitter Protocol class
+ * ActivityPub Transmitter Protocol class
  *
  * To-Do:
- * - Undo Announce
+ * @todo Undo Announce
  */
 class Transmitter
 {
        /**
-        * collects the lost of followers of the given owner
+        * Collects a list of contacts of the given owner
         *
-        * @param array   $owner Owner array
-        * @param integer $page  Page number
+        * @param array     $owner  Owner array
+        * @param int|array $rel    The relevant value(s) contact.rel should match
+        * @param string    $module The name of the relevant AP endpoint module (followers|following)
+        * @param integer   $page   Page number
         *
         * @return array of owners
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
+        * @throws \Exception
         */
-       public static function getFollowers($owner, $page = null)
+       public static function getContacts($owner, $rel, $module, $page = null)
        {
-               $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
-                       'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
-               $count = DBA::count('contact', $condition);
-
-               $data = ['@context' => ActivityPub::CONTEXT];
-               $data['id'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
-               $data['type'] = 'OrderedCollection';
-               $data['totalItems'] = $count;
-
-               // When we hide our friends we will only show the pure number but don't allow more.
-               $profile = Profile::getByUID($owner['uid']);
-               if (!empty($profile['hide-friends'])) {
-                       return $data;
-               }
-
-               if (empty($page)) {
-                       $data['first'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
-               } else {
-                       $data['type'] = 'OrderedCollectionPage';
-                       $list = [];
-
-                       $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
-                       while ($contact = DBA::fetch($contacts)) {
-                               $list[] = $contact['url'];
-                       }
-
-                       if (!empty($list)) {
-                               $data['next'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
-                       }
-
-                       $data['partOf'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
+               $parameters = [
+                       'rel' => $rel,
+                       'uid' => $owner['uid'],
+                       'self' => false,
+                       'deleted' => false,
+                       'hidden' => false,
+                       'archive' => false,
+                       'pending' => false
+               ];
+               $condition = DBA::buildCondition($parameters);
 
-                       $data['orderedItems'] = $list;
-               }
+               $sql = "SELECT COUNT(*) as `count`
+                       FROM `contact`
+                       JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
+                       " . $condition;
 
-               return $data;
-       }
+               $contacts = DBA::fetchFirst($sql, ...$parameters);
 
-       /**
-        * Create list of following contacts
-        *
-        * @param array   $owner Owner array
-        * @param integer $page  Page numbe
-        *
-        * @return array of following contacts
-        * @throws \Friendica\Network\HTTPException\InternalServerErrorException
-        */
-       public static function getFollowing($owner, $page = null)
-       {
-               $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
-                       'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
-               $count = DBA::count('contact', $condition);
+               $modulePath = '/' . $module . '/';
 
                $data = ['@context' => ActivityPub::CONTEXT];
-               $data['id'] = DI::baseUrl() . '/following/' . $owner['nickname'];
+               $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
                $data['type'] = 'OrderedCollection';
-               $data['totalItems'] = $count;
+               $data['totalItems'] = $contacts['count'];
 
                // When we hide our friends we will only show the pure number but don't allow more.
                $profile = Profile::getByUID($owner['uid']);
@@ -120,21 +106,31 @@ class Transmitter
                }
 
                if (empty($page)) {
-                       $data['first'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
+                       $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
                } else {
                        $data['type'] = 'OrderedCollectionPage';
                        $list = [];
 
-                       $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
+                       $sql = "SELECT `contact`.`url`
+                               FROM `contact`
+                               JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
+                               " . $condition . "
+                               LIMIT ?, ?";
+
+                       $parameters[] = ($page - 1) * 100;
+                       $parameters[] = 100;
+
+                       $contacts = DBA::p($sql, ...$parameters);
                        while ($contact = DBA::fetch($contacts)) {
                                $list[] = $contact['url'];
                        }
+                       DBA::close($contacts);
 
                        if (!empty($list)) {
-                               $data['next'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
+                               $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
                        }
 
-                       $data['partOf'] = DI::baseUrl() . '/following/' . $owner['nickname'];
+                       $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
 
                        $data['orderedItems'] = $list;
                }
@@ -157,7 +153,7 @@ class Transmitter
                $public_contact = Contact::getIdForURL($owner['url'], 0, true);
 
                $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
-                       'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
+                       'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
                        'deleted' => false, 'visible' => true, 'moderated' => false];
                $count = DBA::count('item', $condition);
 
@@ -177,8 +173,10 @@ class Transmitter
                        $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
                        while ($item = Item::fetch($items)) {
                                $activity = self::createActivityFromItem($item['id'], true);
+                               $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
+
                                // Only list "Create" activity objects here, no reshares
-                               if (is_array($activity['object']) && ($activity['type'] == 'Create')) {
+                               if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
                                        $list[] = $activity['object'];
                                }
                        }
@@ -225,7 +223,7 @@ class Transmitter
                }
 
                $fields = ['locality', 'region', 'country-name'];
-               $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
+               $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
                if (!DBA::isResult($profile)) {
                        return [];
                }
@@ -248,7 +246,7 @@ class Transmitter
                $data['name'] = $contact['name'];
                $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
                        'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
-               $data['summary'] = $contact['about'];
+               $data['summary'] = BBCode::convert($contact['about'], false);
                $data['url'] = $contact['url'];
                $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
                $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
@@ -325,7 +323,11 @@ class Transmitter
                        }
 
                        foreach ($activity[$element] as $receiver) {
-                               if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
+                               if (empty($receiver)) {
+                                       continue;
+                               }
+
+                               if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
                                        $permissions[$element][] = $item_profile['followers'];
                                } elseif (!in_array($receiver, $exclude)) {
                                        $permissions[$element][] = $receiver;
@@ -363,11 +365,11 @@ class Transmitter
                        }
                }
 
-               if (Config::get('system', 'ap_always_bcc')) {
+               if (DI::config()->get('system', 'ap_always_bcc')) {
                        $always_bcc = true;
                }
 
-               if (self::isAnnounce($item) || Config::get('debug', 'total_ap_delivery')) {
+               if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
                        // Will be activated in a later step
                        $networks = Protocol::FEDERATED;
                } else {
@@ -383,9 +385,9 @@ class Transmitter
                        $actor_profile = APContact::getByURL($item['author-link']);
                }
 
-               $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
+               $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
 
-               if (!$item['private']) {
+               if ($item['private'] != Item::PRIVATE) {
                        // Directly mention the original author upon a quoted reshare.
                        // Else just ensure that the original author receives the reshare.
                        $announce = self::getAnnounceArray($item);
@@ -397,7 +399,12 @@ class Transmitter
 
                        $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
 
-                       $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
+                       // Check if the item is completely public or unlisted
+                       if ($item['private'] == Item::PUBLIC) {
+                               $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
+                       } else {
+                               $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
+                       }
 
                        foreach ($terms as $term) {
                                $profile = APContact::getByURL($term['url'], false);
@@ -451,13 +458,13 @@ class Transmitter
                                                                $data['to'][] = $profile['url'];
                                                        } else {
                                                                $data['cc'][] = $profile['url'];
-                                                               if (!$item['private'] && !empty($actor_profile['followers'])) {
+                                                               if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
                                                                        $data['cc'][] = $actor_profile['followers'];
                                                                }
                                                        }
                                                } else {
                                                        // Public thread parent post always are directed to the followers
-                                                       if (!$item['private'] && !$forum_mode) {
+                                                       if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
                                                                $data['cc'][] = $actor_profile['followers'];
                                                        }
                                                }
@@ -548,7 +555,7 @@ class Transmitter
        {
                $inboxes = [];
 
-               if (Config::get('debug', 'total_ap_delivery')) {
+               if (DI::config()->get('debug', 'total_ap_delivery')) {
                        // Will be activated in a later step
                        $networks = Protocol::FEDERATED;
                } else {
@@ -628,11 +635,11 @@ class Transmitter
                        $blindcopy = in_array($element, ['bto', 'bcc']);
 
                        foreach ($permissions[$element] as $receiver) {
-                               if (Network::isUrlBlocked($receiver)) {
+                               if (empty($receiver) || Network::isUrlBlocked($receiver)) {
                                        continue;
                                }
 
-                               if ($receiver == $item_profile['followers']) {
+                               if ($item_profile && $receiver == $item_profile['followers']) {
                                        $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
                                } else {
                                        if (Contact::isLocal($receiver)) {
@@ -672,6 +679,8 @@ class Transmitter
                        return [];
                }
 
+               $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
+
                $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
 
                // Making the post more compatible for Mastodon by:
@@ -720,7 +729,7 @@ class Transmitter
                        $data = [];
                }
 
-               $data['id'] = $mail['uri'] . '#Create';
+               $data['id'] = $mail['uri'] . '/Create';
                $data['type'] = 'Create';
                $data['actor'] = $mail['author-link'];
                $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
@@ -827,7 +836,7 @@ class Transmitter
 
                $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
 
-               DI::cache()->set($cachekey, $data, Cache::QUARTER_HOUR);
+               DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
                return $data;
        }
 
@@ -884,7 +893,7 @@ class Transmitter
                        $data = [];
                }
 
-               $data['id'] = $item['uri'] . '#' . $type;
+               $data['id'] = $item['uri'] . '/' . $type;
                $data['type'] = $type;
 
                if (Item::isForumPost($item) && ($type != 'Announce')) {
@@ -980,12 +989,12 @@ class Transmitter
        {
                $tags = [];
 
-               $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
+               $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
                foreach ($terms as $term) {
-                       if ($term['type'] == Term::HASHTAG) {
-                               $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
-                               $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
-                       } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
+                       if ($term['type'] == Tag::HASHTAG) {
+                               $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
+                               $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
+                       } else {
                                $contact = Contact::getDetailsByURL($term['url']);
                                if (!empty($contact['addr'])) {
                                        $mention = '@' . $contact['addr'];
@@ -1107,7 +1116,7 @@ class Transmitter
        }
 
        /**
-        * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
+        * Callback function to replace a Friendica style mention in a mention that is used on AP
         *
         * @param array $match Matching values for the callback
         * @return string Replaced mention
@@ -1184,15 +1193,14 @@ class Transmitter
        /**
         * Returns if the post contains sensitive content ("nsfw")
         *
-        * @param integer $item_id
+        * @param integer $uri_id
         *
         * @return boolean
         * @throws \Exception
         */
-       private static function isSensitive($item_id)
+       private static function isSensitive($uri_id)
        {
-               $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
-               return DBA::exists('term', $condition);
+               return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
        }
 
        /**
@@ -1207,7 +1215,7 @@ class Transmitter
        {
                $event = [];
                $event['name'] = $item['event-summary'];
-               $event['content'] = BBCode::convert($item['event-desc'], false, 9);
+               $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
                $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
 
                if (!$item['event-nofinish']) {
@@ -1274,7 +1282,7 @@ class Transmitter
 
                $data['url'] = $item['plink'];
                $data['attributedTo'] = $item['author-link'];
-               $data['sensitive'] = self::isSensitive($item['id']);
+               $data['sensitive'] = self::isSensitive($item['uri-id']);
                $data['context'] = self::fetchContextURLForItem($item);
 
                if (!empty($item['title'])) {
@@ -1286,7 +1294,7 @@ class Transmitter
                $body = $item['body'];
 
                if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
-                       $body = self::prependMentions($body, $permission_block);
+                       $body = self::prependMentions($body, $item['uri-id']);
                }
 
                if ($type == 'Note') {
@@ -1301,7 +1309,7 @@ class Transmitter
                        $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
                        $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
 
-                       $data['content'] = BBCode::convert($body, false, 9);
+                       $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
                }
 
                // The regular "content" field does contain a minimized HTML. This is done since systems like
@@ -1364,7 +1372,7 @@ class Transmitter
                }
 
                // And finally just use the system language
-               return Config::get('system', 'language');
+               return DI::config()->get('system', 'language');
        }
 
        /**
@@ -1379,8 +1387,8 @@ class Transmitter
         */
        private static function createAddTag($item, $data)
        {
-               $object = XML::parseString($item['object'], false);
-               $target = XML::parseString($item["target"], false);
+               $object = XML::parseString($item['object']);
+               $target = XML::parseString($item["target"]);
 
                $data['diaspora:guid'] = $item['guid'];
                $data['actor'] = $item['author-link'];
@@ -1511,14 +1519,14 @@ class Transmitter
        {
                $owner = User::getOwnerDataById($uid);
 
-               $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
+               $suggestion = DI::fsuggest()->getById($suggestion_id);
 
                $data = ['@context' => ActivityPub::CONTEXT,
                        'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
                        'type' => 'Announce',
                        'actor' => $owner['url'],
-                       'object' => $suggestion['url'],
-                       'content' => $suggestion['note'],
+                       'object' => $suggestion->url,
+                       'content' => $suggestion->note,
                        'instrument' => self::getService(),
                        'to' => [ActivityPub::PUBLIC_COLLECTION],
                        'cc' => []];
@@ -1689,7 +1697,7 @@ class Transmitter
 
                if (empty($uid)) {
                        // Fetch the list of administrators
-                       $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
+                       $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
 
                        // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
                        $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
@@ -1835,22 +1843,18 @@ class Transmitter
                HTTPSignature::transmit($signed, $profile['inbox'], $uid);
        }
 
-       private static function prependMentions($body, array $permission_block)
+       private static function prependMentions($body, int $uriid)
        {
-               if (Config::get('system', 'disable_implicit_mentions')) {
-                       return $body;
-               }
-
                $mentions = [];
 
-               foreach ($permission_block['to'] as $profile_url) {
-                       $profile = Contact::getDetailsByURL($profile_url);
+               foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
+                       $profile = Contact::getDetailsByURL($tag['url']);
                        if (!empty($profile['addr'])
                                && $profile['contact-type'] != Contact::TYPE_COMMUNITY
                                && !strstr($body, $profile['addr'])
-                               && !strstr($body, $profile_url)
+                               && !strstr($body, $tag['url'])
                        ) {
-                               $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
+                               $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
                        }
                }