3 * @copyright Copyright (C) 2010-2022, the Friendica project
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\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
32 use Friendica\Database\DBA;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Contact;
36 use Friendica\Model\Conversation;
37 use Friendica\Model\Event;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Model\Post;
45 use Friendica\Protocol\Activity;
46 use Friendica\Protocol\ActivityPub;
47 use Friendica\Protocol\Relay;
48 use Friendica\Util\DateTimeFormat;
49 use Friendica\Util\HTTPSignature;
50 use Friendica\Util\JsonLD;
51 use Friendica\Util\Network;
52 use Friendica\Util\Strings;
53 use Friendica\Worker\Delivery;
56 * ActivityPub Processor Protocol class
60 const CACHEKEY_FETCH_ACTIVITY = 'processor:fetchMissingActivity:';
61 const CACHEKEY_JUST_FETCHED = 'processor:isJustFetched:';
63 * Extracts the tag character (#, @, !) from mention links
68 protected static function normalizeMentionLinks(string $body): string
70 return preg_replace('%\[url=([^\[\]]*)]([#@!])(.*?)\[/url]%ism', '$2[url=$1]$3[/url]', $body);
74 * Convert the language array into a language JSON
76 * @param array $languages
77 * @return string language JSON
79 private static function processLanguages(array $languages): string
81 $codes = array_keys($languages);
83 foreach ($codes as $code) {
91 return json_encode($lang);
94 * Replaces emojis in the body
98 * @param array $emojis
100 * @return string with replaced emojis
102 private static function replaceEmojis(int $uri_id, string $body, array $emojis): string
106 array_column($emojis, 'name'),
107 array_map(function ($emoji) {
108 return '[emoji=' . $emoji['href'] . ']' . $emoji['name'] . '[/emoji]';
113 // We store the emoji here to be able to avoid storing it in the media
114 foreach ($emojis as $emoji) {
115 Post\Link::getByLink($uri_id, $emoji['href']);
121 * Store attached media files in the post-media table
124 * @param array $attachment
127 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
129 if (empty($attachment['url'])) {
133 $data = ['uri-id' => $uriid];
134 $data['type'] = Post\Media::UNKNOWN;
135 $data['url'] = $attachment['url'];
136 $data['mimetype'] = $attachment['mediaType'] ?? null;
137 $data['height'] = $attachment['height'] ?? null;
138 $data['width'] = $attachment['width'] ?? null;
139 $data['size'] = $attachment['size'] ?? null;
140 $data['preview'] = $attachment['image'] ?? null;
141 $data['description'] = $attachment['name'] ?? null;
143 Post\Media::insert($data);
147 * Stire attachment data
149 * @param array $activity
152 private static function storeAttachments(array $activity, array $item)
154 if (empty($activity['attachments'])) {
158 foreach ($activity['attachments'] as $attach) {
159 self::storeAttachmentAsMedia($item['uri-id'], $attach);
164 * Store attachment data
166 * @param array $activity
169 private static function storeQuestion(array $activity, array $item)
171 if (empty($activity['question'])) {
174 $question = ['multiple' => $activity['question']['multiple']];
176 if (!empty($activity['question']['voters'])) {
177 $question['voters'] = $activity['question']['voters'];
180 if (!empty($activity['question']['end-time'])) {
181 $question['end-time'] = DateTimeFormat::utc($activity['question']['end-time']);
184 Post\Question::update($item['uri-id'], $question);
186 foreach ($activity['question']['options'] as $key => $option) {
187 $option = ['name' => $option['name'], 'replies' => $option['replies']];
188 Post\QuestionOption::update($item['uri-id'], $key, $option);
191 Logger::debug('Storing incoming question', ['type' => $activity['type'], 'uri-id' => $item['uri-id'], 'question' => $activity['question']]);
197 * @param array $activity Activity array
198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
199 * @throws \ImagickException
201 public static function updateItem(array $activity)
203 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type'], ['uri' => $activity['id']]);
204 if (!DBA::isResult($item)) {
205 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
206 $item = self::createItem($activity);
211 self::postItem($activity, $item);
215 $item['changed'] = DateTimeFormat::utcNow();
216 $item['edited'] = DateTimeFormat::utc($activity['updated']);
218 $item = self::processContent($activity, $item);
223 self::storeAttachments($activity, $item);
224 self::storeQuestion($activity, $item);
226 Post\History::add($item['uri-id'], $item);
227 Item::update($item, ['uri' => $activity['id']]);
229 Queue::remove($activity);
231 if ($activity['object_type'] == 'as:Event') {
232 $posts = Post::select(['event-id', 'uid'], ["`uri` = ? AND `event-id` > ?", $activity['id'], 0]);
233 while ($post = DBA::fetch($posts)) {
234 self::updateEvent($post['event-id'], $activity);
240 * Update an existing event
242 * @param int $event_id
243 * @param array $activity
245 private static function updateEvent(int $event_id, array $activity)
247 $event = DBA::selectFirst('event', [], ['id' => $event_id]);
249 $event['edited'] = DateTimeFormat::utc($activity['updated']);
250 $event['summary'] = HTML::toBBCode($activity['name']);
251 $event['desc'] = HTML::toBBCode($activity['content']);
252 if (!empty($activity['start-time'])) {
253 $event['start'] = DateTimeFormat::utc($activity['start-time']);
255 if (!empty($activity['end-time'])) {
256 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
258 $event['nofinish'] = empty($event['finish']);
259 $event['location'] = $activity['location'];
261 Logger::info('Updating event', ['uri' => $activity['id'], 'id' => $event_id]);
262 Event::store($event);
266 * Prepares data for a message
268 * @param array $activity Activity array
269 * @param bool $fetch_parents
271 * @return array Internal item
273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274 * @throws \ImagickException
276 public static function createItem(array $activity, bool $fetch_parents = true): array
279 $item['verb'] = Activity::POST;
280 $item['thr-parent'] = $activity['reply-to-id'];
282 if ($activity['reply-to-id'] == $activity['id']) {
283 $item['gravity'] = GRAVITY_PARENT;
284 $item['object-type'] = Activity\ObjectType::NOTE;
286 $item['gravity'] = GRAVITY_COMMENT;
287 $item['object-type'] = Activity\ObjectType::COMMENT;
290 if (!empty($activity['context'])) {
291 $item['conversation'] = $activity['context'];
292 } elseif (!empty($activity['conversation'])) {
293 $item['conversation'] = $activity['conversation'];
296 if (!empty($item['conversation'])) {
297 $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
298 if (!empty($conversation)) {
299 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
300 $item['parent-uri'] = $conversation['uri'];
306 if (empty($activity['author']) && empty($activity['actor'])) {
307 Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
311 if ($fetch_parents && empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
312 $result = self::fetchParent($activity);
313 if (!empty($result)) {
314 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
315 $item['thr-parent'] = $result;
317 } elseif (empty($conversation)) {
322 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
324 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
325 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
329 $item['network'] = Protocol::ACTIVITYPUB;
330 $item['author-link'] = $activity['author'];
331 $item['author-id'] = Contact::getIdForURL($activity['author']);
332 $item['owner-link'] = $activity['actor'];
333 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
335 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
336 $item['private'] = Item::UNLISTED;
337 } elseif (in_array(0, $activity['receiver'])) {
338 $item['private'] = Item::PUBLIC;
340 $item['private'] = Item::PRIVATE;
343 if (!empty($activity['raw'])) {
344 $item['source'] = $activity['raw'];
347 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
349 if (isset($activity['push'])) {
350 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
353 if (!empty($activity['from-relay'])) {
354 $item['direction'] = Conversation::RELAY;
357 if ($activity['object_type'] == 'as:Article') {
358 $item['post-type'] = Item::PT_ARTICLE;
359 } elseif ($activity['object_type'] == 'as:Audio') {
360 $item['post-type'] = Item::PT_AUDIO;
361 } elseif ($activity['object_type'] == 'as:Document') {
362 $item['post-type'] = Item::PT_DOCUMENT;
363 } elseif ($activity['object_type'] == 'as:Event') {
364 $item['post-type'] = Item::PT_EVENT;
365 } elseif ($activity['object_type'] == 'as:Image') {
366 $item['post-type'] = Item::PT_IMAGE;
367 } elseif ($activity['object_type'] == 'as:Page') {
368 $item['post-type'] = Item::PT_PAGE;
369 } elseif ($activity['object_type'] == 'as:Question') {
370 $item['post-type'] = Item::PT_POLL;
371 } elseif ($activity['object_type'] == 'as:Video') {
372 $item['post-type'] = Item::PT_VIDEO;
374 $item['post-type'] = Item::PT_NOTE;
377 $item['isForum'] = false;
379 if (!empty($activity['thread-completion'])) {
380 if ($activity['thread-completion'] != $item['owner-id']) {
381 $actor = Contact::getById($activity['thread-completion'], ['url']);
382 $item['causer-link'] = $actor['url'];
383 $item['causer-id'] = $activity['thread-completion'];
384 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
386 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
387 $item['causer-link'] = $item['owner-link'];
388 $item['causer-id'] = $item['owner-id'];
389 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
392 $item['owner-link'] = $item['author-link'];
393 $item['owner-id'] = $item['author-id'];
395 $actor = APContact::getByURL($item['owner-link'], false);
396 $item['isForum'] = ($actor['type'] == 'Group');
399 $item['uri'] = $activity['id'];
401 if (empty($activity['published']) || empty($activity['updated'])) {
402 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
405 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
406 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
407 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
408 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
410 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
411 if (empty($item['uri-id'])) {
412 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
416 $item = self::processContent($activity, $item);
418 Logger::info('Message was not processed');
422 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
424 self::storeAttachments($activity, $item);
425 self::storeQuestion($activity, $item);
427 // We received the post via AP, so we set the protocol of the server to AP
428 $contact = Contact::getById($item['author-id'], ['gsid']);
429 if (!empty($contact['gsid'])) {
430 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
433 if ($item['author-id'] != $item['owner-id']) {
434 $contact = Contact::getById($item['owner-id'], ['gsid']);
435 if (!empty($contact['gsid'])) {
436 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
444 * Fetch and process parent posts for the given activity
446 * @param array $activity
450 private static function fetchParent(array $activity): string
452 if (self::hasJustBeenFetched($activity['reply-to-id'])) {
453 Logger::notice('We just have tried to fetch this activity. We don\'t try it again.', ['parent' => $activity['reply-to-id']]);
457 $recursion_depth = $activity['recursion-depth'] ?? 0;
459 if ($recursion_depth < DI::config()->get('system', 'max_recursion_depth')) {
460 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
461 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
462 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
463 Logger::notice('The activity is gone, the queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
464 if (!empty($activity['entry-id'])) {
465 Queue::deleteById($activity['entry-id']);
468 } elseif (!empty($result)) {
469 $exists = Post::exists(['uri' => [$result, $activity['reply-to-id']]]);
471 Logger::notice('The activity has been fetched and created.', ['parent' => $result]);
473 } elseif (DI::config()->get('system', 'fetch_by_worker') || DI::config()->get('system', 'decoupled_receiver')) {
474 Logger::notice('The activity has been fetched and will hopefully be created later.', ['parent' => $result]);
476 Logger::notice('The activity exists but has not been created, the queue entry will be deleted.', ['parent' => $result]);
477 if (!empty($activity['entry-id'])) {
478 Queue::deleteById($activity['entry-id']);
483 if (empty($result) && !DI::config()->get('system', 'fetch_by_worker')) {
486 } elseif (self::isActivityGone($activity['reply-to-id'])) {
487 Logger::notice('The activity is gone. We will not spawn a worker. The queue entry will be deleted', ['parent' => $activity['reply-to-id']]);
488 if (!empty($activity['entry-id'])) {
489 Queue::deleteById($activity['entry-id']);
493 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
496 if (Queue::hasWorker($activity['worker-id'] ?? 0)) {
497 Logger::notice('There is already a worker task to fetch the post.', ['id' => $activity['id'], 'parent' => $activity['reply-to-id']]);
501 if (!Fetch::hasWorker($activity['reply-to-id'])) {
502 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
503 Fetch::add($activity['reply-to-id']);
504 $activity['recursion-depth'] = 0;
505 $wid = Worker::add(PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
506 Fetch::setWorkerId($activity['reply-to-id'], $wid);
508 Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
515 * Check if a given activity has recently been fetched
520 private static function hasJustBeenFetched(string $url): bool
522 $cachekey = self::CACHEKEY_JUST_FETCHED . $url;
523 $time = DI::cache()->get($cachekey);
524 if (is_null($time)) {
525 DI::cache()->set($cachekey, time(), Duration::FIVE_MINUTES);
528 return ($time + 300) > time();
532 * Check if a given activity is no longer available
538 public static function isActivityGone(string $url): bool
540 $curlResult = HTTPSignature::fetchRaw($url, 0);
542 if (Network::isUrlBlocked($url)) {
546 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
547 if (in_array($curlResult->getReturnCode(), [404])) {
551 $object = json_decode($curlResult->getBody(), true);
552 if (!empty($object)) {
553 $activity = JsonLD::compact($object);
554 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
564 * @param array $activity
565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
566 * @throws \ImagickException
568 public static function deleteItem(array $activity)
570 $owner = Contact::getIdForURL($activity['actor']);
572 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
573 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
574 Queue::remove($activity);
578 * Prepare the item array for an activity
580 * @param array $activity Activity array
581 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
582 * @throws \ImagickException
584 public static function addTag(array $activity)
586 if (empty($activity['object_content']) || empty($activity['object_id'])) {
590 foreach ($activity['receiver'] as $receiver) {
591 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
592 if (!DBA::isResult($item)) {
593 // We don't fetch missing content for this purpose
597 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
598 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
602 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
603 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
608 * Prepare the item array for an activity
610 * @param array $activity Activity array
611 * @param string $verb Activity verb
612 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
613 * @throws \ImagickException
615 public static function createActivity(array $activity, string $verb)
617 $activity['reply-to-id'] = $activity['object_id'];
618 $item = self::createItem($activity);
623 $item['verb'] = $verb;
624 $item['thr-parent'] = $activity['object_id'];
625 $item['gravity'] = GRAVITY_ACTIVITY;
626 unset($item['post-type']);
627 $item['object-type'] = Activity\ObjectType::NOTE;
629 if (!empty($activity['content'])) {
630 $item['body'] = HTML::toBBCode($activity['content']);
633 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
635 self::postItem($activity, $item);
639 * Fetch the Uri-Id of a post for the "featured" collection
641 * @param array $activity
644 private static function getUriIdForFeaturedCollection(array $activity)
646 $actor = APContact::getByURL($activity['actor']);
651 // Refetch the account when the "featured" collection is missing.
652 // This can be removed in a future version (end of 2022 should be good).
653 if (empty($actor['featured'])) {
654 $actor = APContact::getByURL($activity['actor'], true);
660 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
661 if (empty($parent['uri-id'])) {
662 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
663 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
667 if (!empty($parent['uri-id'])) {
668 return $parent['uri-id'];
675 * Add a post to the "Featured" collection
677 * @param array $activity
679 public static function addToFeaturedCollection(array $activity)
681 $uriid = self::getUriIdForFeaturedCollection($activity);
686 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
688 Post\Collection::add($uriid, Post\Collection::FEATURED);
689 Queue::remove($activity);
693 * Remove a post to the "Featured" collection
695 * @param array $activity
697 public static function removeFromFeaturedCollection(array $activity)
699 $uriid = self::getUriIdForFeaturedCollection($activity);
704 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
706 Post\Collection::remove($uriid, Post\Collection::FEATURED);
707 Queue::remove($activity);
713 * @param array $activity Activity array
716 * @return int event id
719 public static function createEvent(array $activity, array $item): int
721 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
722 $event['desc'] = HTML::toBBCode($activity['content']);
723 if (!empty($activity['start-time'])) {
724 $event['start'] = DateTimeFormat::utc($activity['start-time']);
726 if (!empty($activity['end-time'])) {
727 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
729 $event['nofinish'] = empty($event['finish']);
730 $event['location'] = $activity['location'];
731 $event['cid'] = $item['contact-id'];
732 $event['uid'] = $item['uid'];
733 $event['uri'] = $item['uri'];
734 $event['edited'] = $item['edited'];
735 $event['private'] = $item['private'];
736 $event['guid'] = $item['guid'];
737 $event['plink'] = $item['plink'];
738 $event['network'] = $item['network'];
739 $event['protocol'] = $item['protocol'];
740 $event['direction'] = $item['direction'];
741 $event['source'] = $item['source'];
743 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
744 if (DBA::isResult($ev)) {
745 $event['id'] = $ev['id'];
748 $event_id = Event::store($event);
750 Logger::info('Event was stored', ['id' => $event_id]);
756 * Process the content
758 * @param array $activity Activity array
760 * @return array|bool Returns the item array or false if there was an unexpected occurrence
763 private static function processContent(array $activity, array $item)
765 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
766 $item['title'] = strip_tags($activity['name']);
767 $content = Markdown::toBBCode($activity['content']);
768 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
769 $item['title'] = $activity['name'];
770 $content = $activity['content'];
772 // By default assume "text/html"
773 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
774 $content = HTML::toBBCode($activity['content'] ?? '');
777 $item['title'] = trim(BBCode::toPlaintext($item['title']));
779 if (!empty($activity['languages'])) {
780 $item['language'] = self::processLanguages($activity['languages']);
783 if (!empty($activity['emojis'])) {
784 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
787 $content = self::addMentionLinks($content, $activity['tags']);
789 if (!empty($activity['source'])) {
790 $item['body'] = $activity['source'];
791 $item['raw-body'] = $content;
792 $item['body'] = Item::improveSharedDataInBody($item);
794 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
795 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
796 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
797 if (!DBA::isResult($parent)) {
798 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
801 if (($item['private'] == Item::PRIVATE) && ($parent['private'] != Item::PRIVATE)) {
802 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
806 $content = self::removeImplicitMentionsFromBody($content, $parent);
808 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
809 $item['raw-body'] = $item['body'] = $content;
812 self::storeFromBody($item);
813 self::storeTags($item['uri-id'], $activity['tags']);
815 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
817 $item['location'] = $activity['location'];
819 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
820 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
823 $item['app'] = $activity['generator'];
829 * Store hashtags and mentions
833 private static function storeFromBody(array $item)
835 // Make sure to delete all existing tags (can happen when called via the update functionality)
836 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
838 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
842 * Generate a GUID out of an URL of an ActivityPub post.
844 * @param string $url message URL
845 * @return string with GUID
847 private static function getGUIDByURL(string $url): string
849 $parsed = parse_url($url);
851 $host_hash = hash('crc32', $parsed['host']);
853 unset($parsed["scheme"]);
854 unset($parsed["host"]);
856 $path = implode("/", $parsed);
858 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
862 * Checks if an incoming message is wanted
864 * @param array $activity
866 * @return boolean Is the message wanted?
868 private static function isSolicitedMessage(array $activity, array $item): bool
870 // The checks are split to improve the support when searching why a message was accepted.
871 if (count($activity['receiver']) != 1) {
872 // The message has more than one receiver, so it is wanted.
873 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
877 if ($item['private'] == Item::PRIVATE) {
878 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
879 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
883 if (!empty($activity['from-relay'])) {
884 // We check relay posts at another place. When it arrived here, the message is already checked.
885 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
889 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
890 // Manual completions and completions caused by reshares are allowed without any further checks.
891 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
895 if ($item['gravity'] != GRAVITY_PARENT) {
896 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
897 // This can possibly be improved in the future.
898 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
902 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
903 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
904 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
912 * Creates an item post
914 * @param array $activity Activity data
915 * @param array $item item array
916 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
917 * @throws \ImagickException
919 public static function postItem(array $activity, array $item)
927 ksort($activity['receiver']);
929 if (!self::isSolicitedMessage($activity, $item)) {
930 DBA::delete('item-uri', ['id' => $item['uri-id']]);
934 foreach ($activity['receiver'] as $receiver) {
935 if ($receiver == -1) {
939 $item['uid'] = $receiver;
941 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
943 case Receiver::TARGET_TO:
944 $item['post-reason'] = Item::PR_TO;
946 case Receiver::TARGET_CC:
947 $item['post-reason'] = Item::PR_CC;
949 case Receiver::TARGET_BTO:
950 $item['post-reason'] = Item::PR_BTO;
952 case Receiver::TARGET_BCC:
953 $item['post-reason'] = Item::PR_BCC;
955 case Receiver::TARGET_FOLLOWER:
956 $item['post-reason'] = Item::PR_FOLLOWER;
958 case Receiver::TARGET_ANSWER:
959 $item['post-reason'] = Item::PR_COMMENT;
961 case Receiver::TARGET_GLOBAL:
962 $item['post-reason'] = Item::PR_GLOBAL;
965 $item['post-reason'] = Item::PR_NONE;
968 if (!empty($activity['from-relay'])) {
969 $item['post-reason'] = Item::PR_RELAY;
970 } elseif (!empty($activity['thread-completion'])) {
971 $item['post-reason'] = Item::PR_FETCHED;
972 } elseif (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE]) && !empty($activity['push'])) {
973 $item['post-reason'] = Item::PR_PUSHED;
976 if ($item['isForum'] ?? false) {
977 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
979 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
982 if (($receiver != 0) && empty($item['contact-id'])) {
983 $item['contact-id'] = Contact::getIdForURL($activity['author']);
986 if (!empty($activity['directmessage'])) {
987 self::postMail($activity, $item);
991 if (!($item['isForum'] ?? false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !Contact::isSharingByURL($activity['author'], $receiver)) {
992 if ($item['post-reason'] == Item::PR_BCC) {
993 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id']]);
998 !empty($activity['thread-children-type'])
999 && in_array($activity['thread-children-type'], Receiver::ACTIVITY_TYPES)
1000 && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE
1002 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
1003 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
1010 if ($receiver != 0) {
1011 $user = User::getById($receiver, ['account-type']);
1012 if (!empty($user['account-type'])) {
1013 $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
1017 if (!$is_forum && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
1018 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
1020 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
1021 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
1025 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
1029 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
1032 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
1033 $event_id = self::createEvent($activity, $item);
1035 $item = Event::getItemArrayForImportedId($event_id, $item);
1038 $item_id = Item::insert($item);
1040 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
1043 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
1046 if ($item['uid'] == 0) {
1051 Queue::remove($activity);
1053 if ($success && Queue::hasChildren($item['uri'])) {
1054 Queue::processReplyByUri($item['uri']);
1057 // Store send a follow request for every reshare - but only when the item had been stored
1058 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
1059 $author = APContact::getByURL($item['owner-link'], false);
1060 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
1061 if ($author['type'] != 'Group') {
1062 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
1063 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1069 * Store tags and mentions into the tag table
1071 * @param integer $uriid
1072 * @param array $tags
1074 private static function storeTags(int $uriid, array $tags = null)
1076 foreach ($tags as $tag) {
1077 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1081 $hash = substr($tag['name'], 0, 1);
1083 if ($tag['type'] == 'Mention') {
1084 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1085 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1086 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1087 $tag['name'] = substr($tag['name'], 1);
1089 $type = Tag::IMPLICIT_MENTION;
1091 if (!empty($tag['href'])) {
1092 $apcontact = APContact::getByURL($tag['href']);
1093 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1094 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1097 } elseif ($tag['type'] == 'Hashtag') {
1098 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1099 $tag['name'] = substr($tag['name'], 1);
1101 $type = Tag::HASHTAG;
1104 if (empty($tag['name'])) {
1108 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1112 public static function storeReceivers(int $uriid, array $receivers)
1114 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1115 if (!empty($receivers[$element])) {
1116 foreach ($receivers[$element] as $receiver) {
1117 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1118 $name = Receiver::PUBLIC_COLLECTION;
1120 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
1123 $target = Tag::getTargetType($receiver);
1124 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1125 Tag::store($uriid, $type, $name, $receiver, $target);
1132 * Creates an mail post
1134 * @param array $activity Activity data
1135 * @param array $item item array
1136 * @return int|bool New mail table row id or false on error
1137 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1139 private static function postMail(array $activity, array $item)
1141 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1142 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1146 Logger::info('Direct Message', $item);
1149 $msg['uid'] = $item['uid'];
1151 $msg['contact-id'] = $item['contact-id'];
1153 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1154 $msg['from-name'] = $contact['name'];
1155 $msg['from-url'] = $contact['url'];
1156 $msg['from-photo'] = $contact['photo'];
1158 $msg['uri'] = $item['uri'];
1159 $msg['created'] = $item['created'];
1161 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1162 if (DBA::isResult($parent)) {
1163 $msg['parent-uri'] = $parent['parent-uri'];
1164 $msg['title'] = $parent['title'];
1166 $msg['parent-uri'] = $item['thr-parent'];
1168 if (!empty($item['title'])) {
1169 $msg['title'] = $item['title'];
1170 } elseif (!empty($item['content-warning'])) {
1171 $msg['title'] = $item['content-warning'];
1173 // Trying to generate a title out of the body
1174 $title = $item['body'];
1176 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1177 $title = $matches[3];
1180 $title = trim(BBCode::toPlaintext($title));
1182 if (strlen($title) > 20) {
1183 $title = substr($title, 0, 20) . '...';
1186 $msg['title'] = $title;
1189 $msg['body'] = $item['body'];
1191 return Mail::insert($msg);
1195 * Fetch featured posts from a contact with the given url
1197 * @param string $url
1200 public static function fetchFeaturedPosts(string $url)
1202 Logger::info('Fetch featured posts', ['contact' => $url]);
1204 $apcontact = APContact::getByURL($url);
1205 if (empty($apcontact['featured'])) {
1206 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1210 $pcid = Contact::getIdForURL($url, 0, false);
1212 Logger::info('Contact not found', ['contact' => $url]);
1216 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1217 if (!empty($posts)) {
1218 $old_featured = array_column($posts, 'uri-id');
1223 $featured = ActivityPub::fetchItems($apcontact['featured']);
1224 if (empty($featured)) {
1225 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1227 foreach ($old_featured as $uri_id) {
1228 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1229 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1237 foreach ($featured as $post) {
1238 if (empty($post['id'])) {
1241 $id = Item::fetchByLink($post['id']);
1243 $item = Post::selectFirst(['uri-id', 'featured'], ['id' => $id]);
1244 if (!empty($item['uri-id'])) {
1245 if (!$item['featured']) {
1246 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED);
1247 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1250 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1254 $index = array_search($item['uri-id'], $old_featured);
1255 if (!($index === false)) {
1256 unset($old_featured[$index]);
1262 foreach ($old_featured as $uri_id) {
1263 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1264 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1267 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1270 public static function fetchCachedActivity(string $url, int $uid): array
1272 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . $url;
1273 $object = DI::cache()->get($cachekey);
1275 if (!is_null($object)) {
1276 if (!empty($object)) {
1277 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1279 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1284 $object = ActivityPub::fetchContent($url, $uid);
1285 if (empty($object)) {
1286 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1287 // We perform negative caching.
1288 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1292 if (empty($object['id'])) {
1293 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1296 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1298 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1304 * Fetches missing posts
1306 * @param string $url message URL
1307 * @param array $child activity array with the child of this message
1308 * @param string $relay_actor Relay actor
1309 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1310 * @return string fetched message URL
1311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1312 * @throws \ImagickException
1314 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
1316 if (!empty($child['receiver'])) {
1317 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
1322 $object = self::fetchCachedActivity($url, $uid);
1323 if (empty($object)) {
1329 if (!empty($object['attributedTo'])) {
1330 $attributed_to = $object['attributedTo'];
1331 if (is_array($attributed_to)) {
1332 $compacted = JsonLD::compact($object);
1333 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1335 $signer[] = $attributed_to;
1338 if (!empty($object['actor'])) {
1339 $object_actor = $object['actor'];
1340 } elseif (!empty($attributed_to)) {
1341 $object_actor = $attributed_to;
1347 $signer[] = $object_actor;
1349 if (!empty($child['author'])) {
1350 $actor = $child['author'];
1353 $actor = $object_actor;
1356 if (!empty($object['published'])) {
1357 $published = $object['published'];
1358 } elseif (!empty($child['published'])) {
1359 $published = $child['published'];
1361 $published = DateTimeFormat::utcNow();
1365 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1366 unset($object['@context']);
1367 $activity['id'] = $object['id'];
1368 $activity['to'] = $object['to'] ?? [];
1369 $activity['cc'] = $object['cc'] ?? [];
1370 $activity['actor'] = $actor;
1371 $activity['object'] = $object;
1372 $activity['published'] = $published;
1373 $activity['type'] = 'Create';
1375 $ldactivity = JsonLD::compact($activity);
1377 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 1;
1379 if (!empty($relay_actor)) {
1380 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1381 $ldactivity['completion-mode'] = Receiver::COMPLETION_RELAY;
1382 } elseif (!empty($child['thread-completion'])) {
1383 $ldactivity['thread-completion'] = $child['thread-completion'];
1384 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1386 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1387 $ldactivity['completion-mode'] = $completion;
1390 if (!empty($child['type'])) {
1391 $ldactivity['thread-children-type'] = $child['type'];
1394 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1398 if (($completion == Receiver::COMPLETION_RELAY) && Queue::exists($url, 'as:Create')) {
1399 Logger::notice('Activity has already been queued.', ['url' => $url, 'object' => $activity['id']]);
1400 } elseif (ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer, '', $completion)) {
1401 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1403 Logger::notice('Activity had been fetched and will be processed later.', ['url' => $url, 'entry' => $child['entry-id'] ?? 0, 'completion' => $completion, 'object' => $activity['id']]);
1406 return $activity['id'];
1410 * Test if incoming relay messages should be accepted
1412 * @param array $activity activity array
1413 * @param string $id object ID
1414 * @return boolean true if message is accepted
1416 private static function acceptIncomingMessage(array $activity, string $id): bool
1418 if (empty($activity['as:object'])) {
1419 Logger::info('No object field in activity - accepted', ['id' => $id]);
1423 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1424 $uriid = ItemURI::getIdByURI($replyto ?? '');
1425 if (Post::exists(['uri-id' => $uriid])) {
1426 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1430 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1431 $authorid = Contact::getIdForURL($attributed_to);
1433 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1436 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1437 if (!empty($tags)) {
1438 foreach ($tags as $tag) {
1439 if ($tag['type'] != 'Hashtag') {
1442 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1446 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1450 * perform a "follow" request
1452 * @param array $activity
1454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1455 * @throws \ImagickException
1457 public static function followUser(array $activity)
1459 $uid = User::getIdForURL($activity['object_id']);
1461 Queue::remove($activity);
1465 $owner = User::getOwnerDataById($uid);
1466 if (empty($owner)) {
1470 $cid = Contact::getIdForURL($activity['actor'], $uid);
1472 self::switchContact($cid);
1473 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1477 'author-id' => Contact::getIdForURL($activity['actor']),
1478 'author-link' => $activity['actor'],
1481 // Ensure that the contact has got the right network type
1482 self::switchContact($item['author-id']);
1484 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1485 if ($result === true) {
1486 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1489 $cid = Contact::getIdForURL($activity['actor'], $uid);
1494 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1495 self::transmitPendingEvents($cid, $owner['uid']);
1498 if (empty($contact)) {
1499 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1501 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1502 Queue::remove($activity);
1506 * Transmit pending events to the new follower
1508 * @param integer $cid Contact id
1509 * @param integer $uid User id
1512 private static function transmitPendingEvents(int $cid, int $uid)
1514 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1515 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1517 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1518 while ($event = DBA::fetch($events)) {
1519 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1523 if (DI::config()->get('system', 'bulk_delivery')) {
1524 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1525 Worker::add(PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1527 Worker::add(PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1533 * Update the given profile
1535 * @param array $activity
1536 * @throws \Exception
1538 public static function updatePerson(array $activity)
1540 if (empty($activity['object_id'])) {
1544 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1545 Contact::updateFromProbeByURL($activity['object_id']);
1546 Queue::remove($activity);
1550 * Delete the given profile
1552 * @param array $activity
1554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1556 public static function deletePerson(array $activity)
1558 if (empty($activity['object_id']) || empty($activity['actor'])) {
1559 Logger::info('Empty object id or actor.');
1563 if ($activity['object_id'] != $activity['actor']) {
1564 Logger::info('Object id does not match actor.');
1568 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1569 while ($contact = DBA::fetch($contacts)) {
1570 Contact::remove($contact['id']);
1572 DBA::close($contacts);
1574 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1575 Queue::remove($activity);
1579 * Blocks the user by the contact
1581 * @param array $activity
1583 * @throws \Exception
1585 public static function blockAccount(array $activity)
1587 $cid = Contact::getIdForURL($activity['actor']);
1592 $uid = User::getIdForURL($activity['object_id']);
1597 Contact\User::setIsBlocked($cid, $uid, true);
1599 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1600 Queue::remove($activity);
1604 * Unblocks the user by the contact
1606 * @param array $activity
1608 * @throws \Exception
1610 public static function unblockAccount(array $activity)
1612 $cid = Contact::getIdForURL($activity['actor']);
1617 $uid = User::getIdForURL($activity['object_object']);
1622 Contact\User::setIsBlocked($cid, $uid, false);
1624 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1625 Queue::remove($activity);
1629 * Accept a follow request
1631 * @param array $activity
1632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1633 * @throws \ImagickException
1635 public static function acceptFollowUser(array $activity)
1637 $uid = User::getIdForURL($activity['object_actor']);
1642 $cid = Contact::getIdForURL($activity['actor'], $uid);
1644 Logger::info('No contact found', ['actor' => $activity['actor']]);
1648 self::switchContact($cid);
1650 $fields = ['pending' => false];
1652 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1653 if ($contact['rel'] == Contact::FOLLOWER) {
1654 $fields['rel'] = Contact::FRIEND;
1657 $condition = ['id' => $cid];
1658 Contact::update($fields, $condition);
1659 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1660 Queue::remove($activity);
1664 * Reject a follow request
1666 * @param array $activity
1667 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1668 * @throws \ImagickException
1670 public static function rejectFollowUser(array $activity)
1672 $uid = User::getIdForURL($activity['object_actor']);
1677 $cid = Contact::getIdForURL($activity['actor'], $uid);
1679 Logger::info('No contact found', ['actor' => $activity['actor']]);
1683 self::switchContact($cid);
1685 $contact = Contact::getById($cid, ['rel']);
1686 if ($contact['rel'] == Contact::SHARING) {
1687 Contact::remove($cid);
1688 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1689 } elseif ($contact['rel'] == Contact::FRIEND) {
1690 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1692 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1694 Queue::remove($activity);
1698 * Undo activity like "like" or "dislike"
1700 * @param array $activity
1701 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1702 * @throws \ImagickException
1704 public static function undoActivity(array $activity)
1706 if (empty($activity['object_id'])) {
1710 if (empty($activity['object_actor'])) {
1714 $author_id = Contact::getIdForURL($activity['object_actor']);
1715 if (empty($author_id)) {
1719 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1720 Queue::remove($activity);
1724 * Activity to remove a follower
1726 * @param array $activity
1727 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1728 * @throws \ImagickException
1730 public static function undoFollowUser(array $activity)
1732 $uid = User::getIdForURL($activity['object_object']);
1737 $owner = User::getOwnerDataById($uid);
1738 if (empty($owner)) {
1742 $cid = Contact::getIdForURL($activity['actor'], $uid);
1744 Logger::info('No contact found', ['actor' => $activity['actor']]);
1748 self::switchContact($cid);
1750 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1751 if (!DBA::isResult($contact)) {
1755 Contact::removeFollower($contact);
1756 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1757 Queue::remove($activity);
1761 * Switches a contact to AP if needed
1763 * @param integer $cid Contact ID
1765 * @throws \Exception
1767 private static function switchContact(int $cid)
1769 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1770 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1774 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1775 Contact::updateFromProbe($cid);
1779 * Collects implicit mentions like:
1780 * - the author of the parent item
1781 * - all the mentioned conversants in the parent item
1783 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1785 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1787 private static function getImplicitMentionList(array $parent): array
1789 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1791 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1793 $implicit_mentions = [];
1794 if (empty($parent_author['url'])) {
1795 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1797 $implicit_mentions[] = $parent_author['url'];
1798 $implicit_mentions[] = $parent_author['nurl'];
1799 $implicit_mentions[] = $parent_author['alias'];
1802 if (!empty($parent['alias'])) {
1803 $implicit_mentions[] = $parent['alias'];
1806 foreach ($parent_terms as $term) {
1807 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1808 if (!empty($contact['url'])) {
1809 $implicit_mentions[] = $contact['url'];
1810 $implicit_mentions[] = $contact['nurl'];
1811 $implicit_mentions[] = $contact['alias'];
1815 return $implicit_mentions;
1819 * Strips from the body prepended implicit mentions
1821 * @param string $body
1822 * @param array $parent
1825 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
1827 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1831 $potential_mentions = self::getImplicitMentionList($parent);
1833 $kept_mentions = [];
1835 // Extract one prepended mention at a time from the body
1836 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1837 if (!in_array($matches[2], $potential_mentions)) {
1838 $kept_mentions[] = $matches[1];
1841 $body = $matches[3];
1844 // Re-appending the kept mentions to the body after extraction
1845 $kept_mentions[] = $body;
1847 return implode('', $kept_mentions);
1851 * Adds links to string mentions
1853 * @param string $body
1854 * @param array $tags
1857 protected static function addMentionLinks(string $body, array $tags): string
1859 // This prevents links to be added again to Pleroma-style mention links
1860 $body = self::normalizeMentionLinks($body);
1862 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1863 foreach ($tags as $tag) {
1864 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1868 $hash = substr($tag['name'], 0, 1);
1869 $name = substr($tag['name'], 1);
1870 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1872 $name = $tag['name'];
1875 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);