3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\PageInfo;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Database\DBA;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\Event;
36 use Friendica\Model\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Model\Post;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\Strings;
51 * ActivityPub Processor Protocol class
56 * Converts mentions from Pleroma into the Friendica format
60 * @return string converted body
62 private static function convertMentions($body)
64 $URLSearchString = "^\[\]";
65 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
71 * Convert the language array into a language JSON
73 * @param array $languages
74 * @return string language JSON
76 private static function processLanguages(array $languages)
78 $codes = array_keys($languages);
80 foreach ($codes as $code) {
88 return json_encode($lang);
91 * Replaces emojis in the body
93 * @param array $emojis
96 * @return string with replaced emojis
98 private static function replaceEmojis($body, array $emojis)
102 array_column($emojis, 'name'),
103 array_map(function ($emoji) {
104 return '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
113 * Store attached media files in the post-media table
116 * @param array $attachment
119 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
121 if (empty($attachment['url'])) {
125 $data = ['uri-id' => $uriid];
127 $filetype = strtolower(substr($attachment['mediaType'], 0, strpos($attachment['mediaType'], '/')));
128 if ($filetype == 'image') {
129 $data['type'] = Post\Media::IMAGE;
130 } elseif ($filetype == 'video') {
131 $data['type'] = Post\Media::VIDEO;
132 } elseif ($filetype == 'audio') {
133 $data['type'] = Post\Media::AUDIO;
134 } elseif (in_array($attachment['mediaType'], ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
135 $data['type'] = Post\Media::TORRENT;
137 Logger::info('Unknown type', ['attachment' => $attachment]);
141 $data['url'] = $attachment['url'];
142 $data['mimetype'] = $attachment['mediaType'];
143 $data['height'] = $attachment['height'] ?? null;
144 $data['size'] = $attachment['size'] ?? null;
145 $data['preview'] = $attachment['image'] ?? null;
146 $data['description'] = $attachment['name'] ?? null;
148 Post\Media::insert($data);
152 * Add attachment data to the item array
154 * @param array $activity
157 * @return array array
159 private static function constructAttachList($activity, $item)
161 if (empty($activity['attachments'])) {
165 foreach ($activity['attachments'] as $attach) {
166 switch ($attach['type']) {
169 'url' => $attach['url'],
170 'type' => $attach['type'],
171 'title' => $attach['title'] ?? '',
172 'text' => $attach['desc'] ?? '',
173 'image' => $attach['image'] ?? '',
177 $item['body'] = PageInfo::appendDataToBody($item['body'], $data);
180 self::storeAttachmentAsMedia($item['uri-id'], $attach);
182 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
183 if ($filetype == 'image') {
184 if (!empty($activity['source'])) {
185 foreach ([0, 1, 2] as $size) {
186 if (preg_match('#/photo/.*-' . $size . '\.#ism', $attach['url']) &&
187 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $activity['source']), $attach['url'])) {
191 if (strpos($activity['source'], $attach['url'])) {
196 $item['body'] .= "\n";
198 // image is the preview/thumbnail URL
199 if (!empty($attach['image'])) {
200 $item['body'] .= '[url=' . $attach['url'] . ']';
201 $attach['url'] = $attach['image'];
204 if (empty($attach['name'])) {
205 $item['body'] .= '[img]' . $attach['url'] . '[/img]';
207 $item['body'] .= '[img=' . $attach['url'] . ']' . $attach['name'] . '[/img]';
210 if (!empty($attach['image'])) {
211 $item['body'] .= '[/url]';
213 } elseif ($filetype == 'audio') {
214 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
218 $item['body'] = '[audio]' . $attach['url'] . "[/audio]\n" . $item['body'];
219 } elseif ($filetype == 'video') {
220 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
224 $item['body'] = '[video]' . $attach['url'] . "[/video]\n" . $item['body'];
235 * @param array $activity Activity array
236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238 public static function updateItem($activity)
240 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
241 if (!DBA::isResult($item)) {
242 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
243 $item = self::createItem($activity);
244 self::postItem($activity, $item);
248 $item['changed'] = DateTimeFormat::utcNow();
249 $item['edited'] = DateTimeFormat::utc($activity['updated']);
251 $item = self::processContent($activity, $item);
253 $item = self::constructAttachList($activity, $item);
259 Item::update($item, ['uri' => $activity['id']]);
263 * Prepares data for a message
265 * @param array $activity Activity array
266 * @return array Internal item
267 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 * @throws \ImagickException
270 public static function createItem($activity)
273 $item['verb'] = Activity::POST;
274 $item['thr-parent'] = $activity['reply-to-id'];
276 if ($activity['reply-to-id'] == $activity['id']) {
277 $item['gravity'] = GRAVITY_PARENT;
278 $item['object-type'] = Activity\ObjectType::NOTE;
280 $item['gravity'] = GRAVITY_COMMENT;
281 $item['object-type'] = Activity\ObjectType::COMMENT;
284 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
285 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
286 self::fetchMissingActivity($activity['reply-to-id'], $activity);
289 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
291 /// @todo What to do with $activity['context']?
292 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
293 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
297 $item['network'] = Protocol::ACTIVITYPUB;
298 $item['author-link'] = $activity['author'];
299 $item['author-id'] = Contact::getIdForURL($activity['author']);
300 $item['owner-link'] = $activity['actor'];
301 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
303 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
304 $item['private'] = Item::UNLISTED;
305 } elseif (in_array(0, $activity['receiver'])) {
306 $item['private'] = Item::PUBLIC;
308 $item['private'] = Item::PRIVATE;
311 if (!empty($activity['raw'])) {
312 $item['source'] = $activity['raw'];
313 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
314 $item['conversation-href'] = $activity['context'] ?? '';
315 $item['conversation-uri'] = $activity['conversation'] ?? '';
317 if (isset($activity['push'])) {
318 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
322 if (!empty($activity['from-relay'])) {
323 $item['direction'] = Conversation::RELAY;
326 $item['isForum'] = false;
328 if (!empty($activity['thread-completion'])) {
329 if ($activity['thread-completion'] != $item['owner-id']) {
330 $actor = Contact::getById($activity['thread-completion'], ['url']);
331 $item['causer-link'] = $actor['url'];
332 $item['causer-id'] = $activity['thread-completion'];
333 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
335 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
336 $item['causer-link'] = $item['owner-link'];
337 $item['causer-id'] = $item['owner-id'];
338 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
341 $item['owner-link'] = $item['author-link'];
342 $item['owner-id'] = $item['author-id'];
344 $actor = APContact::getByURL($item['owner-link'], false);
345 $item['isForum'] = ($actor['type'] == 'Group');
348 $item['uri'] = $activity['id'];
350 $item['created'] = DateTimeFormat::utc($activity['published']);
351 $item['edited'] = DateTimeFormat::utc($activity['updated']);
352 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
353 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
355 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
356 if (empty($item['uri-id'])) {
357 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
361 $item = self::processContent($activity, $item);
363 Logger::info('Message was not processed');
367 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
369 $item = self::constructAttachList($activity, $item);
371 // We received the post via AP, so we set the protocol of the server to AP
372 $contact = Contact::getById($item['author-id'], ['gsid']);
373 if (!empty($contact['gsid'])) {
374 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
377 if ($item['author-id'] != $item['owner-id']) {
378 $contact = Contact::getById($item['owner-id'], ['gsid']);
379 if (!empty($contact['gsid'])) {
380 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
390 * @param array $activity
391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
392 * @throws \ImagickException
394 public static function deleteItem($activity)
396 $owner = Contact::getIdForURL($activity['actor']);
398 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
399 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
403 * Prepare the item array for an activity
405 * @param array $activity Activity array
406 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
407 * @throws \ImagickException
409 public static function addTag($activity)
411 if (empty($activity['object_content']) || empty($activity['object_id'])) {
415 foreach ($activity['receiver'] as $receiver) {
416 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
417 if (!DBA::isResult($item)) {
418 // We don't fetch missing content for this purpose
422 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
423 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
427 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
428 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
433 * Prepare the item array for an activity
435 * @param array $activity Activity array
436 * @param string $verb Activity verb
437 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
438 * @throws \ImagickException
440 public static function createActivity($activity, $verb)
442 $item = self::createItem($activity);
443 $item['verb'] = $verb;
444 $item['thr-parent'] = $activity['object_id'];
445 $item['gravity'] = GRAVITY_ACTIVITY;
446 $item['object-type'] = Activity\ObjectType::NOTE;
448 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
450 self::postItem($activity, $item);
456 * @param array $activity Activity array
460 public static function createEvent($activity, $item)
462 $event['summary'] = HTML::toBBCode($activity['name']);
463 $event['desc'] = HTML::toBBCode($activity['content']);
464 $event['start'] = $activity['start-time'];
465 $event['finish'] = $activity['end-time'];
466 $event['nofinish'] = empty($event['finish']);
467 $event['location'] = $activity['location'];
468 $event['adjust'] = true;
469 $event['cid'] = $item['contact-id'];
470 $event['uid'] = $item['uid'];
471 $event['uri'] = $item['uri'];
472 $event['edited'] = $item['edited'];
473 $event['private'] = $item['private'];
474 $event['guid'] = $item['guid'];
475 $event['plink'] = $item['plink'];
476 $event['network'] = $item['network'];
477 $event['protocol'] = $item['protocol'];
478 $event['direction'] = $item['direction'];
479 $event['source'] = $item['source'];
481 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
482 $ev = DBA::selectFirst('event', ['id'], $condition);
483 if (DBA::isResult($ev)) {
484 $event['id'] = $ev['id'];
487 $event_id = Event::store($event);
488 Logger::info('Event was stored', ['id' => $event_id]);
492 * Process the content
494 * @param array $activity Activity array
496 * @return array|bool Returns the item array or false if there was an unexpected occurrence
499 private static function processContent($activity, $item)
501 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
502 $item['title'] = Markdown::toBBCode($activity['name']);
503 $content = Markdown::toBBCode($activity['content']);
504 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
505 $item['title'] = $activity['name'];
506 $content = $activity['content'];
508 // By default assume "text/html"
509 $item['title'] = HTML::toBBCode($activity['name']);
510 $content = HTML::toBBCode($activity['content']);
513 if (!empty($activity['languages'])) {
514 $item['language'] = self::processLanguages($activity['languages']);
517 if (!empty($activity['emojis'])) {
518 $content = self::replaceEmojis($content, $activity['emojis']);
521 $content = self::convertMentions($content);
523 if (!empty($activity['source'])) {
524 $item['body'] = $activity['source'];
525 $item['raw-body'] = $content;
527 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
528 $item_private = !in_array(0, $activity['item_receiver']);
529 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
530 if (!DBA::isResult($parent)) {
531 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
534 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
535 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
539 $content = self::removeImplicitMentionsFromBody($content, $parent);
541 $item['content-warning'] = HTML::toBBCode($activity['summary']);
542 $item['raw-body'] = $item['body'] = $content;
545 self::storeFromBody($item);
546 self::storeTags($item['uri-id'], $activity['tags']);
548 $item['location'] = $activity['location'];
550 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
551 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
554 $item['app'] = $activity['generator'];
560 * Store hashtags and mentions
564 private static function storeFromBody(array $item)
566 // Make sure to delete all existing tags (can happen when called via the update functionality)
567 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
569 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
573 * Generate a GUID out of an URL
575 * @param string $url message URL
576 * @return string with GUID
578 private static function getGUIDByURL(string $url)
580 $parsed = parse_url($url);
582 $host_hash = hash('crc32', $parsed['host']);
584 unset($parsed["scheme"]);
585 unset($parsed["host"]);
587 $path = implode("/", $parsed);
589 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
593 * Creates an item post
595 * @param array $activity Activity data
596 * @param array $item item array
597 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
598 * @throws \ImagickException
600 public static function postItem(array $activity, array $item)
607 ksort($activity['receiver']);
609 foreach ($activity['receiver'] as $receiver) {
610 if ($receiver == -1) {
614 $item['uid'] = $receiver;
616 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
618 case Receiver::TARGET_TO:
619 $item['post-type'] = Item::PT_TO;
621 case Receiver::TARGET_CC:
622 $item['post-type'] = Item::PT_CC;
624 case Receiver::TARGET_BTO:
625 $item['post-type'] = Item::PT_BTO;
627 case Receiver::TARGET_BCC:
628 $item['post-type'] = Item::PT_BCC;
630 case Receiver::TARGET_FOLLOWER:
631 $item['post-type'] = Item::PT_FOLLOWER;
633 case Receiver::TARGET_ANSWER:
634 $item['post-type'] = Item::PT_COMMENT;
636 case Receiver::TARGET_GLOBAL:
637 $item['post-type'] = Item::PT_GLOBAL;
640 $item['post-type'] = Item::PT_ARTICLE;
643 if (!empty($activity['from-relay'])) {
644 $item['post-type'] = Item::PT_RELAY;
645 } elseif (!empty($activity['thread-completion'])) {
646 $item['post-type'] = Item::PT_FETCHED;
649 if ($item['isForum'] ?? false) {
650 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
652 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
655 if (($receiver != 0) && empty($item['contact-id'])) {
656 $item['contact-id'] = Contact::getIdForURL($activity['author']);
659 if (!empty($activity['directmessage'])) {
660 self::postMail($activity, $item);
664 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
665 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
667 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
668 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
672 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
676 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
679 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
680 self::createEvent($activity, $item);
683 $item_id = Item::insert($item);
685 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
687 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
690 if ($item['uid'] == 0) {
695 // Store send a follow request for every reshare - but only when the item had been stored
696 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
697 $author = APContact::getByURL($item['owner-link'], false);
698 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
699 if ($author['type'] != 'Group') {
700 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
701 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
707 * Store tags and mentions into the tag table
709 * @param integer $uriid
712 private static function storeTags(int $uriid, array $tags = null)
714 foreach ($tags as $tag) {
715 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
719 $hash = substr($tag['name'], 0, 1);
721 if ($tag['type'] == 'Mention') {
722 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
723 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
724 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
725 $tag['name'] = substr($tag['name'], 1);
727 $type = Tag::IMPLICIT_MENTION;
729 if (!empty($tag['href'])) {
730 $apcontact = APContact::getByURL($tag['href']);
731 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
732 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
735 } elseif ($tag['type'] == 'Hashtag') {
736 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
737 $tag['name'] = substr($tag['name'], 1);
739 $type = Tag::HASHTAG;
742 if (empty($tag['name'])) {
746 Tag::store($uriid, $type, $tag['name'], $tag['href']);
751 * Creates an mail post
753 * @param array $activity Activity data
754 * @param array $item item array
755 * @return int|bool New mail table row id or false on error
756 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
758 private static function postMail($activity, $item)
760 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
761 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
765 Logger::info('Direct Message', $item);
768 $msg['uid'] = $item['uid'];
770 $msg['contact-id'] = $item['contact-id'];
772 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
773 $msg['from-name'] = $contact['name'];
774 $msg['from-url'] = $contact['url'];
775 $msg['from-photo'] = $contact['photo'];
777 $msg['uri'] = $item['uri'];
778 $msg['created'] = $item['created'];
780 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
781 if (DBA::isResult($parent)) {
782 $msg['parent-uri'] = $parent['parent-uri'];
783 $msg['title'] = $parent['title'];
785 $msg['parent-uri'] = $item['thr-parent'];
787 if (!empty($item['title'])) {
788 $msg['title'] = $item['title'];
789 } elseif (!empty($item['content-warning'])) {
790 $msg['title'] = $item['content-warning'];
792 // Trying to generate a title out of the body
793 $title = $item['body'];
795 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
796 $title = $matches[3];
799 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
801 if (strlen($title) > 20) {
802 $title = substr($title, 0, 20) . '...';
805 $msg['title'] = $title;
808 $msg['body'] = $item['body'];
810 return Mail::insert($msg);
814 * Fetches missing posts
816 * @param string $url message URL
817 * @param array $child activity array with the child of this message
818 * @param string $relay_actor Relay actor
819 * @return string fetched message URL
820 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
822 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '')
824 if (!empty($child['receiver'])) {
825 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
830 $object = ActivityPub::fetchContent($url, $uid);
831 if (empty($object)) {
832 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
836 if (empty($object['id'])) {
837 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
841 if (!empty($object['actor'])) {
842 $object_actor = $object['actor'];
843 } elseif (!empty($object['attributedTo'])) {
844 $object_actor = $object['attributedTo'];
845 if (is_array($object_actor)) {
846 $compacted = JsonLD::compact($object);
847 $object_actor = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
854 $signer = [$object_actor];
856 if (!empty($child['author'])) {
857 $actor = $child['author'];
860 $actor = $object_actor;
863 if (!empty($object['published'])) {
864 $published = $object['published'];
865 } elseif (!empty($child['published'])) {
866 $published = $child['published'];
868 $published = DateTimeFormat::utcNow();
872 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
873 unset($object['@context']);
874 $activity['id'] = $object['id'];
875 $activity['to'] = $object['to'] ?? [];
876 $activity['cc'] = $object['cc'] ?? [];
877 $activity['actor'] = $actor;
878 $activity['object'] = $object;
879 $activity['published'] = $published;
880 $activity['type'] = 'Create';
882 $ldactivity = JsonLD::compact($activity);
884 if (!empty($relay_actor)) {
885 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
886 } elseif (!empty($child['thread-completion'])) {
887 $ldactivity['thread-completion'] = $child['thread-completion'];
889 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
892 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
896 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
898 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
900 return $activity['id'];
904 * Test if incoming relay messages should be accepted
906 * @param array $activity activity array
907 * @param string $id object ID
908 * @return boolean true if message is accepted
910 private static function acceptIncomingMessage(array $activity, string $id)
912 if (empty($activity['as:object'])) {
913 Logger::info('No object field in activity - accepted', ['id' => $id]);
917 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
918 $uriid = ItemURI::getIdByURI($replyto);
919 if (Post::exists(['uri-id' => $uriid])) {
920 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
924 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
925 $authorid = Contact::getIdForURL($attributed_to);
927 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value'));
930 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
932 foreach ($tags as $tag) {
933 if ($tag['type'] != 'Hashtag') {
936 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
940 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
944 * perform a "follow" request
946 * @param array $activity
947 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948 * @throws \ImagickException
950 public static function followUser($activity)
952 $uid = User::getIdForURL($activity['object_id']);
957 $owner = User::getOwnerDataById($uid);
962 $cid = Contact::getIdForURL($activity['actor'], $uid);
964 self::switchContact($cid);
965 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
968 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
969 'author-link' => $activity['actor']];
971 // Ensure that the contact has got the right network type
972 self::switchContact($item['author-id']);
974 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
975 if ($result === true) {
976 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
979 $cid = Contact::getIdForURL($activity['actor'], $uid);
984 if (empty($contact)) {
985 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
988 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
992 * Update the given profile
994 * @param array $activity
997 public static function updatePerson($activity)
999 if (empty($activity['object_id'])) {
1003 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1004 Contact::updateFromProbeByURL($activity['object_id']);
1008 * Delete the given profile
1010 * @param array $activity
1011 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013 public static function deletePerson($activity)
1015 if (empty($activity['object_id']) || empty($activity['actor'])) {
1016 Logger::info('Empty object id or actor.');
1020 if ($activity['object_id'] != $activity['actor']) {
1021 Logger::info('Object id does not match actor.');
1025 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1026 while ($contact = DBA::fetch($contacts)) {
1027 Contact::remove($contact['id']);
1029 DBA::close($contacts);
1031 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1035 * Accept a follow request
1037 * @param array $activity
1038 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1039 * @throws \ImagickException
1041 public static function acceptFollowUser($activity)
1043 $uid = User::getIdForURL($activity['object_actor']);
1048 $cid = Contact::getIdForURL($activity['actor'], $uid);
1050 Logger::info('No contact found', ['actor' => $activity['actor']]);
1054 self::switchContact($cid);
1056 $fields = ['pending' => false];
1058 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1059 if ($contact['rel'] == Contact::FOLLOWER) {
1060 $fields['rel'] = Contact::FRIEND;
1063 $condition = ['id' => $cid];
1064 DBA::update('contact', $fields, $condition);
1065 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1069 * Reject a follow request
1071 * @param array $activity
1072 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1073 * @throws \ImagickException
1075 public static function rejectFollowUser($activity)
1077 $uid = User::getIdForURL($activity['object_actor']);
1082 $cid = Contact::getIdForURL($activity['actor'], $uid);
1084 Logger::info('No contact found', ['actor' => $activity['actor']]);
1088 self::switchContact($cid);
1090 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
1091 Contact::remove($cid);
1092 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1094 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1099 * Undo activity like "like" or "dislike"
1101 * @param array $activity
1102 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1103 * @throws \ImagickException
1105 public static function undoActivity($activity)
1107 if (empty($activity['object_id'])) {
1111 if (empty($activity['object_actor'])) {
1115 $author_id = Contact::getIdForURL($activity['object_actor']);
1116 if (empty($author_id)) {
1120 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1124 * Activity to remove a follower
1126 * @param array $activity
1127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128 * @throws \ImagickException
1130 public static function undoFollowUser($activity)
1132 $uid = User::getIdForURL($activity['object_object']);
1137 $owner = User::getOwnerDataById($uid);
1138 if (empty($owner)) {
1142 $cid = Contact::getIdForURL($activity['actor'], $uid);
1144 Logger::info('No contact found', ['actor' => $activity['actor']]);
1148 self::switchContact($cid);
1150 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1151 if (!DBA::isResult($contact)) {
1155 Contact::removeFollower($owner, $contact);
1156 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1160 * Switches a contact to AP if needed
1162 * @param integer $cid Contact ID
1163 * @throws \Exception
1165 private static function switchContact($cid)
1167 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1168 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1172 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1173 Contact::updateFromProbe($cid);
1177 * Collects implicit mentions like:
1178 * - the author of the parent item
1179 * - all the mentioned conversants in the parent item
1181 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1185 private static function getImplicitMentionList(array $parent)
1187 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1189 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1191 $implicit_mentions = [];
1192 if (empty($parent_author['url'])) {
1193 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1195 $implicit_mentions[] = $parent_author['url'];
1196 $implicit_mentions[] = $parent_author['nurl'];
1197 $implicit_mentions[] = $parent_author['alias'];
1200 if (!empty($parent['alias'])) {
1201 $implicit_mentions[] = $parent['alias'];
1204 foreach ($parent_terms as $term) {
1205 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1206 if (!empty($contact['url'])) {
1207 $implicit_mentions[] = $contact['url'];
1208 $implicit_mentions[] = $contact['nurl'];
1209 $implicit_mentions[] = $contact['alias'];
1213 return $implicit_mentions;
1217 * Strips from the body prepended implicit mentions
1219 * @param string $body
1220 * @param array $parent
1223 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1225 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1229 $potential_mentions = self::getImplicitMentionList($parent);
1231 $kept_mentions = [];
1233 // Extract one prepended mention at a time from the body
1234 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1235 if (!in_array($matches[2], $potential_mentions)) {
1236 $kept_mentions[] = $matches[1];
1239 $body = $matches[3];
1242 // Re-appending the kept mentions to the body after extraction
1243 $kept_mentions[] = $body;
1245 return implode('', $kept_mentions);