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 * @return array Internal item
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 public static function createItem(array $activity): array
276 $item['verb'] = Activity::POST;
277 $item['thr-parent'] = $activity['reply-to-id'];
279 if ($activity['reply-to-id'] == $activity['id']) {
280 $item['gravity'] = GRAVITY_PARENT;
281 $item['object-type'] = Activity\ObjectType::NOTE;
283 $item['gravity'] = GRAVITY_COMMENT;
284 $item['object-type'] = Activity\ObjectType::COMMENT;
287 if (!empty($activity['context'])) {
288 $item['conversation'] = $activity['context'];
289 } elseif (!empty($activity['conversation'])) {
290 $item['conversation'] = $activity['conversation'];
293 if (!empty($item['conversation'])) {
294 $conversation = Post::selectFirstThread(['uri'], ['conversation' => $item['conversation']]);
295 if (!empty($conversation)) {
296 Logger::debug('Got conversation', ['conversation' => $item['conversation'], 'parent' => $conversation]);
297 $item['parent-uri'] = $conversation['uri'];
303 if (empty($activity['author']) && empty($activity['actor'])) {
304 Logger::notice('Missing author and actor. We quit here.', ['activity' => $activity]);
308 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
309 if (self::hasJustBeenFetched($activity['reply-to-id'])) {
310 Logger::notice('We just have tried to fetch this activity. We don\'t try it again.', ['parent' => $activity['reply-to-id']]);
311 $fetch_by_worker = false;
312 if (empty($conversation)) {
316 $recursion_depth = $activity['recursion-depth'] ?? 0;
317 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
318 if ($recursion_depth < DI::config()->get('system', 'max_recursion_depth')) {
319 $result = self::fetchMissingActivity($activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
320 $fetch_by_worker = empty($result);
321 if (empty($result) && self::isActivityGone($activity['reply-to-id'])) {
322 if (!empty($activity['entry-id'])) {
323 Queue::deleteById($activity['entry-id']);
325 if (empty($conversation)) {
330 Logger::notice('Recursion level is too high.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
331 $fetch_by_worker = true;
335 if ($fetch_by_worker && Queue::hasWorker($activity)) {
336 Logger::notice('There is already a worker task to fetch the post.', ['id' => $activity['id'], 'parent' => $activity['reply-to-id']]);
337 $fetch_by_worker = false;
338 if (empty($conversation)) {
343 if ($fetch_by_worker) {
344 Logger::notice('Fetching is done by worker.', ['parent' => $activity['reply-to-id'], 'recursion-depth' => $recursion_depth]);
345 $activity['recursion-depth'] = 0;
346 if (!Fetch::hasWorker($activity['reply-to-id'])) {
347 Fetch::add($activity['reply-to-id']);
348 $wid = Worker::add(PRIORITY_HIGH, 'FetchMissingActivity', $activity['reply-to-id'], $activity, '', Receiver::COMPLETION_AUTO);
349 Fetch::setWorkerId($activity['reply-to-id'], $wid);
350 Queue::setWorkerId($activity, $wid);
352 Logger::debug('Activity will already be fetched via a worker.', ['url' => $activity['reply-to-id']]);
354 if (empty($conversation)) {
357 } elseif (!empty($result)) {
358 if (($item['thr-parent'] != $result) && Post::exists(['uri' => $result])) {
359 $item['thr-parent'] = $result;
364 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
366 if (empty($conversation) && empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
367 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
371 $item['network'] = Protocol::ACTIVITYPUB;
372 $item['author-link'] = $activity['author'];
373 $item['author-id'] = Contact::getIdForURL($activity['author']);
374 $item['owner-link'] = $activity['actor'];
375 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
377 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
378 $item['private'] = Item::UNLISTED;
379 } elseif (in_array(0, $activity['receiver'])) {
380 $item['private'] = Item::PUBLIC;
382 $item['private'] = Item::PRIVATE;
385 if (!empty($activity['raw'])) {
386 $item['source'] = $activity['raw'];
389 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
391 if (isset($activity['push'])) {
392 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
395 if (!empty($activity['from-relay'])) {
396 $item['direction'] = Conversation::RELAY;
399 if ($activity['object_type'] == 'as:Article') {
400 $item['post-type'] = Item::PT_ARTICLE;
401 } elseif ($activity['object_type'] == 'as:Audio') {
402 $item['post-type'] = Item::PT_AUDIO;
403 } elseif ($activity['object_type'] == 'as:Document') {
404 $item['post-type'] = Item::PT_DOCUMENT;
405 } elseif ($activity['object_type'] == 'as:Event') {
406 $item['post-type'] = Item::PT_EVENT;
407 } elseif ($activity['object_type'] == 'as:Image') {
408 $item['post-type'] = Item::PT_IMAGE;
409 } elseif ($activity['object_type'] == 'as:Page') {
410 $item['post-type'] = Item::PT_PAGE;
411 } elseif ($activity['object_type'] == 'as:Question') {
412 $item['post-type'] = Item::PT_POLL;
413 } elseif ($activity['object_type'] == 'as:Video') {
414 $item['post-type'] = Item::PT_VIDEO;
416 $item['post-type'] = Item::PT_NOTE;
419 $item['isForum'] = false;
421 if (!empty($activity['thread-completion'])) {
422 if ($activity['thread-completion'] != $item['owner-id']) {
423 $actor = Contact::getById($activity['thread-completion'], ['url']);
424 $item['causer-link'] = $actor['url'];
425 $item['causer-id'] = $activity['thread-completion'];
426 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
428 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
429 $item['causer-link'] = $item['owner-link'];
430 $item['causer-id'] = $item['owner-id'];
431 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
434 $item['owner-link'] = $item['author-link'];
435 $item['owner-id'] = $item['author-id'];
437 $actor = APContact::getByURL($item['owner-link'], false);
438 $item['isForum'] = ($actor['type'] == 'Group');
441 $item['uri'] = $activity['id'];
443 if (empty($activity['published']) || empty($activity['updated'])) {
444 DI::logger()->notice('published or updated keys are empty for activity', ['activity' => $activity, 'callstack' => System::callstack(10)]);
447 $item['created'] = DateTimeFormat::utc($activity['published'] ?? 'now');
448 $item['edited'] = DateTimeFormat::utc($activity['updated'] ?? 'now');
449 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
450 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
452 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
453 if (empty($item['uri-id'])) {
454 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
458 $item = self::processContent($activity, $item);
460 Logger::info('Message was not processed');
464 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
466 self::storeAttachments($activity, $item);
467 self::storeQuestion($activity, $item);
469 // We received the post via AP, so we set the protocol of the server to AP
470 $contact = Contact::getById($item['author-id'], ['gsid']);
471 if (!empty($contact['gsid'])) {
472 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
475 if ($item['author-id'] != $item['owner-id']) {
476 $contact = Contact::getById($item['owner-id'], ['gsid']);
477 if (!empty($contact['gsid'])) {
478 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
486 * Check if a given activity has recently been fetched
491 private static function hasJustBeenFetched(string $url): bool
493 $cachekey = self::CACHEKEY_JUST_FETCHED . $url;
494 $time = DI::cache()->get($cachekey);
495 if (is_null($time)) {
496 DI::cache()->set($cachekey, time(), Duration::FIVE_MINUTES);
499 return ($time + 300) > time();
503 * Check if a given activity is no longer available
509 public static function isActivityGone(string $url): bool
511 $curlResult = HTTPSignature::fetchRaw($url, 0);
513 if (Network::isUrlBlocked($url)) {
517 // @todo To ensure that the remote system is working correctly, we can check if the "Content-Type" contains JSON
518 if (in_array($curlResult->getReturnCode(), [404])) {
522 $object = json_decode($curlResult->getBody(), true);
523 if (!empty($object)) {
524 $activity = JsonLD::compact($object);
525 if (JsonLD::fetchElement($activity, '@type') == 'as:Tombstone') {
535 * @param array $activity
536 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
537 * @throws \ImagickException
539 public static function deleteItem(array $activity)
541 $owner = Contact::getIdForURL($activity['actor']);
543 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
544 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
545 Queue::remove($activity);
549 * Prepare the item array for an activity
551 * @param array $activity Activity array
552 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
553 * @throws \ImagickException
555 public static function addTag(array $activity)
557 if (empty($activity['object_content']) || empty($activity['object_id'])) {
561 foreach ($activity['receiver'] as $receiver) {
562 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
563 if (!DBA::isResult($item)) {
564 // We don't fetch missing content for this purpose
568 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
569 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
573 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
574 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
579 * Prepare the item array for an activity
581 * @param array $activity Activity array
582 * @param string $verb Activity verb
583 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
584 * @throws \ImagickException
586 public static function createActivity(array $activity, string $verb)
588 $activity['reply-to-id'] = $activity['object_id'];
589 $item = self::createItem($activity);
594 $item['verb'] = $verb;
595 $item['thr-parent'] = $activity['object_id'];
596 $item['gravity'] = GRAVITY_ACTIVITY;
597 unset($item['post-type']);
598 $item['object-type'] = Activity\ObjectType::NOTE;
600 if (!empty($activity['content'])) {
601 $item['body'] = HTML::toBBCode($activity['content']);
604 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
606 self::postItem($activity, $item);
610 * Fetch the Uri-Id of a post for the "featured" collection
612 * @param array $activity
615 private static function getUriIdForFeaturedCollection(array $activity)
617 $actor = APContact::getByURL($activity['actor']);
622 // Refetch the account when the "featured" collection is missing.
623 // This can be removed in a future version (end of 2022 should be good).
624 if (empty($actor['featured'])) {
625 $actor = APContact::getByURL($activity['actor'], true);
631 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
632 if (empty($parent['uri-id'])) {
633 if (self::fetchMissingActivity($activity['object_id'], $activity, '', Receiver::COMPLETION_AUTO)) {
634 $parent = Post::selectFirst(['uri-id'], ['uri' => $activity['object_id']]);
638 if (!empty($parent['uri-id'])) {
639 return $parent['uri-id'];
646 * Add a post to the "Featured" collection
648 * @param array $activity
650 public static function addToFeaturedCollection(array $activity)
652 $uriid = self::getUriIdForFeaturedCollection($activity);
657 Logger::debug('Add post to featured collection', ['uri-id' => $uriid]);
659 Post\Collection::add($uriid, Post\Collection::FEATURED);
660 Queue::remove($activity);
664 * Remove a post to the "Featured" collection
666 * @param array $activity
668 public static function removeFromFeaturedCollection(array $activity)
670 $uriid = self::getUriIdForFeaturedCollection($activity);
675 Logger::debug('Remove post from featured collection', ['uri-id' => $uriid]);
677 Post\Collection::remove($uriid, Post\Collection::FEATURED);
678 Queue::remove($activity);
684 * @param array $activity Activity array
687 * @return int event id
690 public static function createEvent(array $activity, array $item): int
692 $event['summary'] = HTML::toBBCode($activity['name'] ?: $activity['summary']);
693 $event['desc'] = HTML::toBBCode($activity['content']);
694 if (!empty($activity['start-time'])) {
695 $event['start'] = DateTimeFormat::utc($activity['start-time']);
697 if (!empty($activity['end-time'])) {
698 $event['finish'] = DateTimeFormat::utc($activity['end-time']);
700 $event['nofinish'] = empty($event['finish']);
701 $event['location'] = $activity['location'];
702 $event['cid'] = $item['contact-id'];
703 $event['uid'] = $item['uid'];
704 $event['uri'] = $item['uri'];
705 $event['edited'] = $item['edited'];
706 $event['private'] = $item['private'];
707 $event['guid'] = $item['guid'];
708 $event['plink'] = $item['plink'];
709 $event['network'] = $item['network'];
710 $event['protocol'] = $item['protocol'];
711 $event['direction'] = $item['direction'];
712 $event['source'] = $item['source'];
714 $ev = DBA::selectFirst('event', ['id'], ['uri' => $item['uri'], 'uid' => $item['uid']]);
715 if (DBA::isResult($ev)) {
716 $event['id'] = $ev['id'];
719 $event_id = Event::store($event);
721 Logger::info('Event was stored', ['id' => $event_id]);
727 * Process the content
729 * @param array $activity Activity array
731 * @return array|bool Returns the item array or false if there was an unexpected occurrence
734 private static function processContent(array $activity, array $item)
736 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
737 $item['title'] = strip_tags($activity['name']);
738 $content = Markdown::toBBCode($activity['content']);
739 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
740 $item['title'] = $activity['name'];
741 $content = $activity['content'];
743 // By default assume "text/html"
744 $item['title'] = HTML::toBBCode($activity['name'] ?? '');
745 $content = HTML::toBBCode($activity['content'] ?? '');
748 $item['title'] = trim(BBCode::toPlaintext($item['title']));
750 if (!empty($activity['languages'])) {
751 $item['language'] = self::processLanguages($activity['languages']);
754 if (!empty($activity['emojis'])) {
755 $content = self::replaceEmojis($item['uri-id'], $content, $activity['emojis']);
758 $content = self::addMentionLinks($content, $activity['tags']);
760 if (!empty($activity['source'])) {
761 $item['body'] = $activity['source'];
762 $item['raw-body'] = $content;
763 $item['body'] = Item::improveSharedDataInBody($item);
765 $parent_uri = $item['parent-uri'] ?? $item['thr-parent'];
766 if (empty($activity['directmessage']) && ($parent_uri != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
767 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $parent_uri]);
768 if (!DBA::isResult($parent)) {
769 Logger::warning('Unknown parent item.', ['uri' => $parent_uri]);
772 if (($item['private'] == Item::PRIVATE) && ($parent['private'] != Item::PRIVATE)) {
773 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
777 $content = self::removeImplicitMentionsFromBody($content, $parent);
779 $item['content-warning'] = HTML::toBBCode($activity['summary'] ?? '');
780 $item['raw-body'] = $item['body'] = $content;
783 self::storeFromBody($item);
784 self::storeTags($item['uri-id'], $activity['tags']);
786 self::storeReceivers($item['uri-id'], $activity['receiver_urls'] ?? []);
788 $item['location'] = $activity['location'];
790 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
791 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
794 $item['app'] = $activity['generator'];
800 * Store hashtags and mentions
804 private static function storeFromBody(array $item)
806 // Make sure to delete all existing tags (can happen when called via the update functionality)
807 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
809 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
813 * Generate a GUID out of an URL of an ActivityPub post.
815 * @param string $url message URL
816 * @return string with GUID
818 private static function getGUIDByURL(string $url): string
820 $parsed = parse_url($url);
822 $host_hash = hash('crc32', $parsed['host']);
824 unset($parsed["scheme"]);
825 unset($parsed["host"]);
827 $path = implode("/", $parsed);
829 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
833 * Checks if an incoming message is wanted
835 * @param array $activity
837 * @return boolean Is the message wanted?
839 private static function isSolicitedMessage(array $activity, array $item): bool
841 // The checks are split to improve the support when searching why a message was accepted.
842 if (count($activity['receiver']) != 1) {
843 // The message has more than one receiver, so it is wanted.
844 Logger::debug('Message has got several receivers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
848 if ($item['private'] == Item::PRIVATE) {
849 // We only look at public posts here. Private posts are expected to be intentionally posted to the single receiver.
850 Logger::debug('Message is private - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
854 if (!empty($activity['from-relay'])) {
855 // We check relay posts at another place. When it arrived here, the message is already checked.
856 Logger::debug('Message is a relay post that is already checked - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
860 if (in_array($activity['completion-mode'] ?? Receiver::COMPLETION_NONE, [Receiver::COMPLETION_MANUAL, Receiver::COMPLETION_ANNOUCE])) {
861 // Manual completions and completions caused by reshares are allowed without any further checks.
862 Logger::debug('Message is in completion mode - accepted', ['mode' => $activity['completion-mode'], 'uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
866 if ($item['gravity'] != GRAVITY_PARENT) {
867 // We cannot reliably check at this point if a comment or activity belongs to an accepted post or needs to be fetched
868 // This can possibly be improved in the future.
869 Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
873 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
874 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::ACTIVITYPUB)) {
875 Logger::debug('Post is accepted because of the relay settings', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
883 * Creates an item post
885 * @param array $activity Activity data
886 * @param array $item item array
887 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
888 * @throws \ImagickException
890 public static function postItem(array $activity, array $item)
898 ksort($activity['receiver']);
900 if (!self::isSolicitedMessage($activity, $item)) {
901 DBA::delete('item-uri', ['id' => $item['uri-id']]);
905 foreach ($activity['receiver'] as $receiver) {
906 if ($receiver == -1) {
910 $item['uid'] = $receiver;
912 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
914 case Receiver::TARGET_TO:
915 $item['post-reason'] = Item::PR_TO;
917 case Receiver::TARGET_CC:
918 $item['post-reason'] = Item::PR_CC;
920 case Receiver::TARGET_BTO:
921 $item['post-reason'] = Item::PR_BTO;
923 case Receiver::TARGET_BCC:
924 $item['post-reason'] = Item::PR_BCC;
926 case Receiver::TARGET_FOLLOWER:
927 $item['post-reason'] = Item::PR_FOLLOWER;
929 case Receiver::TARGET_ANSWER:
930 $item['post-reason'] = Item::PR_COMMENT;
932 case Receiver::TARGET_GLOBAL:
933 $item['post-reason'] = Item::PR_GLOBAL;
936 $item['post-reason'] = Item::PR_NONE;
939 if (!empty($activity['from-relay'])) {
940 $item['post-reason'] = Item::PR_RELAY;
941 } elseif (!empty($activity['thread-completion'])) {
942 $item['post-reason'] = Item::PR_FETCHED;
943 } elseif (in_array($item['post-reason'], [Item::PR_GLOBAL, Item::PR_NONE]) && !empty($activity['push'])) {
944 $item['post-reason'] = Item::PR_PUSHED;
947 if ($item['isForum'] ?? false) {
948 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
950 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
953 if (($receiver != 0) && empty($item['contact-id'])) {
954 $item['contact-id'] = Contact::getIdForURL($activity['author']);
957 if (!empty($activity['directmessage'])) {
958 self::postMail($activity, $item);
962 if (!($item['isForum'] ?? false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT) && !Contact::isSharingByURL($activity['author'], $receiver)) {
963 if ($item['post-reason'] == Item::PR_BCC) {
964 Logger::info('Top level post via BCC from a non sharer, ignoring', ['uid' => $receiver, 'contact' => $item['contact-id']]);
969 !empty($activity['thread-children-type'])
970 && in_array($activity['thread-children-type'], Receiver::ACTIVITY_TYPES)
971 && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') != Item::COMPLETION_LIKE
973 Logger::info('Top level post from thread completion from a non sharer had been initiated via an activity, ignoring',
974 ['type' => $activity['thread-children-type'], 'user' => $item['uid'], 'causer' => $item['causer-link'], 'author' => $activity['author'], 'url' => $item['uri']]);
981 if ($receiver != 0) {
982 $user = User::getById($receiver, ['account-type']);
983 if (!empty($user['account-type'])) {
984 $is_forum = ($user['account-type'] == User::ACCOUNT_TYPE_COMMUNITY);
988 if (!$is_forum && DI::pConfig()->get($receiver, 'system', 'accept_only_sharer') == Item::COMPLETION_NONE && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
989 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
991 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
992 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
996 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
1000 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
1003 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
1004 $event_id = self::createEvent($activity, $item);
1006 $item = Event::getItemArrayForImportedId($event_id, $item);
1009 $item_id = Item::insert($item);
1011 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
1014 Logger::notice('Item insertion aborted', ['uri' => $item['uri'], 'uid' => $item['uid']]);
1017 if ($item['uid'] == 0) {
1022 Queue::remove($activity);
1024 if ($success && Queue::hasChildren($item['uri'])) {
1025 Worker::add(PRIORITY_HIGH, 'ProcessReplyByUri', $item['uri']);
1028 // Store send a follow request for every reshare - but only when the item had been stored
1029 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && !empty($item['author-link']) && ($item['author-link'] != $item['owner-link'])) {
1030 $author = APContact::getByURL($item['owner-link'], false);
1031 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
1032 if ($author['type'] != 'Group') {
1033 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
1034 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
1040 * Store tags and mentions into the tag table
1042 * @param integer $uriid
1043 * @param array $tags
1045 private static function storeTags(int $uriid, array $tags = null)
1047 foreach ($tags as $tag) {
1048 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1052 $hash = substr($tag['name'], 0, 1);
1054 if ($tag['type'] == 'Mention') {
1055 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
1056 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
1057 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
1058 $tag['name'] = substr($tag['name'], 1);
1060 $type = Tag::IMPLICIT_MENTION;
1062 if (!empty($tag['href'])) {
1063 $apcontact = APContact::getByURL($tag['href']);
1064 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
1065 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
1068 } elseif ($tag['type'] == 'Hashtag') {
1069 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
1070 $tag['name'] = substr($tag['name'], 1);
1072 $type = Tag::HASHTAG;
1075 if (empty($tag['name'])) {
1079 Tag::store($uriid, $type, $tag['name'], $tag['href']);
1083 public static function storeReceivers(int $uriid, array $receivers)
1085 foreach (['as:to' => Tag::TO, 'as:cc' => Tag::CC, 'as:bto' => Tag::BTO, 'as:bcc' => Tag::BCC] as $element => $type) {
1086 if (!empty($receivers[$element])) {
1087 foreach ($receivers[$element] as $receiver) {
1088 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
1089 $name = Receiver::PUBLIC_COLLECTION;
1091 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
1094 $target = Tag::getTargetType($receiver);
1095 Logger::debug('Got target type', ['type' => $target, 'url' => $receiver]);
1096 Tag::store($uriid, $type, $name, $receiver, $target);
1103 * Creates an mail post
1105 * @param array $activity Activity data
1106 * @param array $item item array
1107 * @return int|bool New mail table row id or false on error
1108 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1110 private static function postMail(array $activity, array $item)
1112 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
1113 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
1117 Logger::info('Direct Message', $item);
1120 $msg['uid'] = $item['uid'];
1122 $msg['contact-id'] = $item['contact-id'];
1124 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
1125 $msg['from-name'] = $contact['name'];
1126 $msg['from-url'] = $contact['url'];
1127 $msg['from-photo'] = $contact['photo'];
1129 $msg['uri'] = $item['uri'];
1130 $msg['created'] = $item['created'];
1132 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
1133 if (DBA::isResult($parent)) {
1134 $msg['parent-uri'] = $parent['parent-uri'];
1135 $msg['title'] = $parent['title'];
1137 $msg['parent-uri'] = $item['thr-parent'];
1139 if (!empty($item['title'])) {
1140 $msg['title'] = $item['title'];
1141 } elseif (!empty($item['content-warning'])) {
1142 $msg['title'] = $item['content-warning'];
1144 // Trying to generate a title out of the body
1145 $title = $item['body'];
1147 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
1148 $title = $matches[3];
1151 $title = trim(BBCode::toPlaintext($title));
1153 if (strlen($title) > 20) {
1154 $title = substr($title, 0, 20) . '...';
1157 $msg['title'] = $title;
1160 $msg['body'] = $item['body'];
1162 return Mail::insert($msg);
1166 * Fetch featured posts from a contact with the given url
1168 * @param string $url
1171 public static function fetchFeaturedPosts(string $url)
1173 Logger::info('Fetch featured posts', ['contact' => $url]);
1175 $apcontact = APContact::getByURL($url);
1176 if (empty($apcontact['featured'])) {
1177 Logger::info('Contact does not have a featured collection', ['contact' => $url]);
1181 $pcid = Contact::getIdForURL($url, 0, false);
1183 Logger::info('Contact not found', ['contact' => $url]);
1187 $posts = Post\Collection::selectToArrayForContact($pcid, Post\Collection::FEATURED);
1188 if (!empty($posts)) {
1189 $old_featured = array_column($posts, 'uri-id');
1194 $featured = ActivityPub::fetchItems($apcontact['featured']);
1195 if (empty($featured)) {
1196 Logger::info('Contact does not have featured posts', ['contact' => $url]);
1198 foreach ($old_featured as $uri_id) {
1199 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1200 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1208 foreach ($featured as $post) {
1209 if (empty($post['id'])) {
1212 $id = Item::fetchByLink($post['id']);
1214 $item = Post::selectFirst(['uri-id', 'featured'], ['id' => $id]);
1215 if (!empty($item['uri-id'])) {
1216 if (!$item['featured']) {
1217 Post\Collection::add($item['uri-id'], Post\Collection::FEATURED);
1218 Logger::debug('Added featured post', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1221 Logger::debug('Post already had been featured', ['uri-id' => $item['uri-id'], 'contact' => $url]);
1225 $index = array_search($item['uri-id'], $old_featured);
1226 if (!($index === false)) {
1227 unset($old_featured[$index]);
1233 foreach ($old_featured as $uri_id) {
1234 Post\Collection::remove($uri_id, Post\Collection::FEATURED);
1235 Logger::debug('Removed no longer featured post', ['uri-id' => $uri_id, 'contact' => $url]);
1238 Logger::info('Fetched featured posts', ['new' => $new, 'old' => $old, 'contact' => $url]);
1241 public static function fetchCachedActivity(string $url, int $uid): array
1243 $cachekey = self::CACHEKEY_FETCH_ACTIVITY . $uid . ':' . $url;
1244 $object = DI::cache()->get($cachekey);
1246 if (!is_null($object)) {
1247 if (!empty($object)) {
1248 Logger::debug('Fetch from cache', ['url' => $url, 'uid' => $uid]);
1250 Logger::debug('Fetch from negative cache', ['url' => $url, 'uid' => $uid]);
1255 $object = ActivityPub::fetchContent($url, $uid);
1256 if (empty($object)) {
1257 Logger::notice('Activity was not fetchable, aborting.', ['url' => $url, 'uid' => $uid]);
1258 // We perform negative caching.
1259 DI::cache()->set($cachekey, [], Duration::FIVE_MINUTES);
1263 if (empty($object['id'])) {
1264 Logger::notice('Activity has got not id, aborting. ', ['url' => $url, 'object' => $object]);
1267 DI::cache()->set($cachekey, $object, Duration::FIVE_MINUTES);
1269 Logger::debug('Activity was fetched successfully', ['url' => $url, 'uid' => $uid]);
1275 * Fetches missing posts
1277 * @param string $url message URL
1278 * @param array $child activity array with the child of this message
1279 * @param string $relay_actor Relay actor
1280 * @param int $completion Completion mode, see Receiver::COMPLETION_*
1281 * @return string fetched message URL
1282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1283 * @throws \ImagickException
1285 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '', int $completion = Receiver::COMPLETION_MANUAL): string
1287 if (!empty($child['receiver'])) {
1288 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
1293 $object = self::fetchCachedActivity($url, $uid);
1294 if (empty($object)) {
1300 if (!empty($object['attributedTo'])) {
1301 $attributed_to = $object['attributedTo'];
1302 if (is_array($attributed_to)) {
1303 $compacted = JsonLD::compact($object);
1304 $attributed_to = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
1306 $signer[] = $attributed_to;
1309 if (!empty($object['actor'])) {
1310 $object_actor = $object['actor'];
1311 } elseif (!empty($attributed_to)) {
1312 $object_actor = $attributed_to;
1318 $signer[] = $object_actor;
1320 if (!empty($child['author'])) {
1321 $actor = $child['author'];
1324 $actor = $object_actor;
1327 if (!empty($object['published'])) {
1328 $published = $object['published'];
1329 } elseif (!empty($child['published'])) {
1330 $published = $child['published'];
1332 $published = DateTimeFormat::utcNow();
1336 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
1337 unset($object['@context']);
1338 $activity['id'] = $object['id'];
1339 $activity['to'] = $object['to'] ?? [];
1340 $activity['cc'] = $object['cc'] ?? [];
1341 $activity['actor'] = $actor;
1342 $activity['object'] = $object;
1343 $activity['published'] = $published;
1344 $activity['type'] = 'Create';
1346 $ldactivity = JsonLD::compact($activity);
1348 $ldactivity['recursion-depth'] = !empty($child['recursion-depth']) ? $child['recursion-depth'] + 1 : 1;
1350 if (!empty($relay_actor)) {
1351 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
1352 $ldactivity['completion-mode'] = Receiver::COMPLETION_RELAY;
1353 } elseif (!empty($child['thread-completion'])) {
1354 $ldactivity['thread-completion'] = $child['thread-completion'];
1355 $ldactivity['completion-mode'] = $child['completion-mode'] ?? Receiver::COMPLETION_NONE;
1357 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
1358 $ldactivity['completion-mode'] = $completion;
1361 if (!empty($child['type'])) {
1362 $ldactivity['thread-children-type'] = $child['type'];
1365 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
1369 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
1371 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
1373 return $activity['id'];
1377 * Test if incoming relay messages should be accepted
1379 * @param array $activity activity array
1380 * @param string $id object ID
1381 * @return boolean true if message is accepted
1383 private static function acceptIncomingMessage(array $activity, string $id): bool
1385 if (empty($activity['as:object'])) {
1386 Logger::info('No object field in activity - accepted', ['id' => $id]);
1390 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
1391 $uriid = ItemURI::getIdByURI($replyto ?? '');
1392 if (Post::exists(['uri-id' => $uriid])) {
1393 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
1397 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
1398 $authorid = Contact::getIdForURL($attributed_to);
1400 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value') ?? '');
1403 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
1404 if (!empty($tags)) {
1405 foreach ($tags as $tag) {
1406 if ($tag['type'] != 'Hashtag') {
1409 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
1413 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
1417 * perform a "follow" request
1419 * @param array $activity
1421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1422 * @throws \ImagickException
1424 public static function followUser(array $activity)
1426 $uid = User::getIdForURL($activity['object_id']);
1428 Queue::remove($activity);
1432 $owner = User::getOwnerDataById($uid);
1433 if (empty($owner)) {
1437 $cid = Contact::getIdForURL($activity['actor'], $uid);
1439 self::switchContact($cid);
1440 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1444 'author-id' => Contact::getIdForURL($activity['actor']),
1445 'author-link' => $activity['actor'],
1448 // Ensure that the contact has got the right network type
1449 self::switchContact($item['author-id']);
1451 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1452 if ($result === true) {
1453 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1456 $cid = Contact::getIdForURL($activity['actor'], $uid);
1461 if ($result && DI::config()->get('system', 'transmit_pending_events') && ($owner['contact-type'] == Contact::TYPE_COMMUNITY)) {
1462 self::transmitPendingEvents($cid, $owner['uid']);
1465 if (empty($contact)) {
1466 Contact::update(['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1468 Logger::notice('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1469 Queue::remove($activity);
1473 * Transmit pending events to the new follower
1475 * @param integer $cid Contact id
1476 * @param integer $uid User id
1479 private static function transmitPendingEvents(int $cid, int $uid)
1481 $account = DBA::selectFirst('account-user-view', ['ap-inbox', 'ap-sharedinbox'], ['id' => $cid]);
1482 $inbox = $account['ap-sharedinbox'] ?: $account['ap-inbox'];
1484 $events = DBA::select('event', ['id'], ["`uid` = ? AND `start` > ? AND `type` != ?", $uid, DateTimeFormat::utcNow(), 'birthday']);
1485 while ($event = DBA::fetch($events)) {
1486 $post = Post::selectFirst(['id', 'uri-id', 'created'], ['event-id' => $event['id']]);
1490 if (DI::config()->get('system', 'bulk_delivery')) {
1491 Post\Delivery::add($post['uri-id'], $uid, $inbox, $post['created'], Delivery::POST, [$cid]);
1492 Worker::add(PRIORITY_HIGH, 'APDelivery', '', 0, $inbox, 0);
1494 Worker::add(PRIORITY_HIGH, 'APDelivery', Delivery::POST, $post['id'], $inbox, $uid, [$cid], $post['uri-id']);
1500 * Update the given profile
1502 * @param array $activity
1503 * @throws \Exception
1505 public static function updatePerson(array $activity)
1507 if (empty($activity['object_id'])) {
1511 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1512 Contact::updateFromProbeByURL($activity['object_id']);
1513 Queue::remove($activity);
1517 * Delete the given profile
1519 * @param array $activity
1521 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1523 public static function deletePerson(array $activity)
1525 if (empty($activity['object_id']) || empty($activity['actor'])) {
1526 Logger::info('Empty object id or actor.');
1530 if ($activity['object_id'] != $activity['actor']) {
1531 Logger::info('Object id does not match actor.');
1535 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1536 while ($contact = DBA::fetch($contacts)) {
1537 Contact::remove($contact['id']);
1539 DBA::close($contacts);
1541 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1542 Queue::remove($activity);
1546 * Blocks the user by the contact
1548 * @param array $activity
1550 * @throws \Exception
1552 public static function blockAccount(array $activity)
1554 $cid = Contact::getIdForURL($activity['actor']);
1559 $uid = User::getIdForURL($activity['object_id']);
1564 Contact\User::setIsBlocked($cid, $uid, true);
1566 Logger::info('Contact blocked user', ['contact' => $cid, 'user' => $uid]);
1567 Queue::remove($activity);
1571 * Unblocks the user by the contact
1573 * @param array $activity
1575 * @throws \Exception
1577 public static function unblockAccount(array $activity)
1579 $cid = Contact::getIdForURL($activity['actor']);
1584 $uid = User::getIdForURL($activity['object_object']);
1589 Contact\User::setIsBlocked($cid, $uid, false);
1591 Logger::info('Contact unblocked user', ['contact' => $cid, 'user' => $uid]);
1592 Queue::remove($activity);
1596 * Accept a follow request
1598 * @param array $activity
1599 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1600 * @throws \ImagickException
1602 public static function acceptFollowUser(array $activity)
1604 $uid = User::getIdForURL($activity['object_actor']);
1609 $cid = Contact::getIdForURL($activity['actor'], $uid);
1611 Logger::info('No contact found', ['actor' => $activity['actor']]);
1615 self::switchContact($cid);
1617 $fields = ['pending' => false];
1619 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1620 if ($contact['rel'] == Contact::FOLLOWER) {
1621 $fields['rel'] = Contact::FRIEND;
1624 $condition = ['id' => $cid];
1625 Contact::update($fields, $condition);
1626 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1627 Queue::remove($activity);
1631 * Reject a follow request
1633 * @param array $activity
1634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1635 * @throws \ImagickException
1637 public static function rejectFollowUser(array $activity)
1639 $uid = User::getIdForURL($activity['object_actor']);
1644 $cid = Contact::getIdForURL($activity['actor'], $uid);
1646 Logger::info('No contact found', ['actor' => $activity['actor']]);
1650 self::switchContact($cid);
1652 $contact = Contact::getById($cid, ['rel']);
1653 if ($contact['rel'] == Contact::SHARING) {
1654 Contact::remove($cid);
1655 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1656 } elseif ($contact['rel'] == Contact::FRIEND) {
1657 Contact::update(['rel' => Contact::FOLLOWER], ['id' => $cid]);
1659 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1661 Queue::remove($activity);
1665 * Undo activity like "like" or "dislike"
1667 * @param array $activity
1668 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1669 * @throws \ImagickException
1671 public static function undoActivity(array $activity)
1673 if (empty($activity['object_id'])) {
1677 if (empty($activity['object_actor'])) {
1681 $author_id = Contact::getIdForURL($activity['object_actor']);
1682 if (empty($author_id)) {
1686 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1687 Queue::remove($activity);
1691 * Activity to remove a follower
1693 * @param array $activity
1694 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1695 * @throws \ImagickException
1697 public static function undoFollowUser(array $activity)
1699 $uid = User::getIdForURL($activity['object_object']);
1704 $owner = User::getOwnerDataById($uid);
1705 if (empty($owner)) {
1709 $cid = Contact::getIdForURL($activity['actor'], $uid);
1711 Logger::info('No contact found', ['actor' => $activity['actor']]);
1715 self::switchContact($cid);
1717 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1718 if (!DBA::isResult($contact)) {
1722 Contact::removeFollower($contact);
1723 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1724 Queue::remove($activity);
1728 * Switches a contact to AP if needed
1730 * @param integer $cid Contact ID
1732 * @throws \Exception
1734 private static function switchContact(int $cid)
1736 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1737 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1741 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1742 Contact::updateFromProbe($cid);
1746 * Collects implicit mentions like:
1747 * - the author of the parent item
1748 * - all the mentioned conversants in the parent item
1750 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1752 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1754 private static function getImplicitMentionList(array $parent): array
1756 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1758 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1760 $implicit_mentions = [];
1761 if (empty($parent_author['url'])) {
1762 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1764 $implicit_mentions[] = $parent_author['url'];
1765 $implicit_mentions[] = $parent_author['nurl'];
1766 $implicit_mentions[] = $parent_author['alias'];
1769 if (!empty($parent['alias'])) {
1770 $implicit_mentions[] = $parent['alias'];
1773 foreach ($parent_terms as $term) {
1774 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1775 if (!empty($contact['url'])) {
1776 $implicit_mentions[] = $contact['url'];
1777 $implicit_mentions[] = $contact['nurl'];
1778 $implicit_mentions[] = $contact['alias'];
1782 return $implicit_mentions;
1786 * Strips from the body prepended implicit mentions
1788 * @param string $body
1789 * @param array $parent
1792 private static function removeImplicitMentionsFromBody(string $body, array $parent): string
1794 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1798 $potential_mentions = self::getImplicitMentionList($parent);
1800 $kept_mentions = [];
1802 // Extract one prepended mention at a time from the body
1803 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1804 if (!in_array($matches[2], $potential_mentions)) {
1805 $kept_mentions[] = $matches[1];
1808 $body = $matches[3];
1811 // Re-appending the kept mentions to the body after extraction
1812 $kept_mentions[] = $body;
1814 return implode('', $kept_mentions);
1818 * Adds links to string mentions
1820 * @param string $body
1821 * @param array $tags
1824 protected static function addMentionLinks(string $body, array $tags): string
1826 // This prevents links to be added again to Pleroma-style mention links
1827 $body = self::normalizeMentionLinks($body);
1829 $body = BBCode::performWithEscapedTags($body, ['url'], function ($body) use ($tags) {
1830 foreach ($tags as $tag) {
1831 if (empty($tag['name']) || empty($tag['type']) || empty($tag['href']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
1835 $hash = substr($tag['name'], 0, 1);
1836 $name = substr($tag['name'], 1);
1837 if (!in_array($hash, Tag::TAG_CHARACTER)) {
1839 $name = $tag['name'];
1842 $body = str_replace($tag['name'], $hash . '[url=' . $tag['href'] . ']' . $name . '[/url]', $body);