3 * @copyright Copyright (C) 2010-2021, 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\PageInfo;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Database\DBA;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\Event;
36 use Friendica\Model\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Mail;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Model\Post;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\Strings;
51 * ActivityPub Processor Protocol class
56 * Converts mentions from Pleroma into the Friendica format
60 * @return string converted body
62 private static function convertMentions($body)
64 $URLSearchString = "^\[\]";
65 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
71 * Convert the language array into a language JSON
73 * @param array $languages
74 * @return string language JSON
76 private static function processLanguages(array $languages)
78 $codes = array_keys($languages);
80 foreach ($codes as $code) {
88 return json_encode($lang);
91 * Replaces emojis in the body
93 * @param array $emojis
96 * @return string with replaced emojis
98 private static function replaceEmojis($body, array $emojis)
102 array_column($emojis, 'name'),
103 array_map(function ($emoji) {
104 return '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
113 * Store attached media files in the post-media table
116 * @param array $attachment
119 private static function storeAttachmentAsMedia(int $uriid, array $attachment)
121 if (empty($attachment['url'])) {
125 $data = ['uri-id' => $uriid];
127 $filetype = strtolower(substr($attachment['mediaType'], 0, strpos($attachment['mediaType'], '/')));
128 if ($filetype == 'image') {
129 $data['type'] = Post\Media::IMAGE;
130 } elseif ($filetype == 'video') {
131 $data['type'] = Post\Media::VIDEO;
132 } elseif ($filetype == 'audio') {
133 $data['type'] = Post\Media::AUDIO;
134 } elseif (in_array($attachment['mediaType'], ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
135 $data['type'] = Post\Media::TORRENT;
137 Logger::info('Unknown type', ['attachment' => $attachment]);
141 $data['url'] = $attachment['url'];
142 $data['mimetype'] = $attachment['mediaType'];
143 $data['height'] = $attachment['height'] ?? null;
144 $data['size'] = $attachment['size'] ?? null;
145 $data['preview'] = $attachment['image'] ?? null;
146 $data['description'] = $attachment['name'] ?? null;
148 Post\Media::insert($data);
152 * Add attachment data to the item array
154 * @param array $activity
157 * @return array array
159 private static function constructAttachList($activity, $item)
161 if (empty($activity['attachments'])) {
168 foreach ($activity['attachments'] as $attach) {
169 switch ($attach['type']) {
172 'url' => $attach['url'],
173 'type' => $attach['type'],
174 'title' => $attach['title'] ?? '',
175 'text' => $attach['desc'] ?? '',
176 'image' => $attach['image'] ?? '',
180 $item['body'] = PageInfo::appendDataToBody($item['body'], $data);
183 self::storeAttachmentAsMedia($item['uri-id'], $attach);
185 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
186 if ($filetype == 'image') {
187 if (!empty($activity['source'])) {
188 foreach ([0, 1, 2] as $size) {
189 if (preg_match('#/photo/.*-' . $size . '\.#ism', $attach['url']) &&
190 strpos(preg_replace('#(/photo/.*)-[012]\.#ism', '$1-' . $size . '.', $activity['source']), $attach['url'])) {
194 if (strpos($activity['source'], $attach['url'])) {
199 // image is the preview/thumbnail URL
200 if (!empty($attach['image'])) {
201 $media = '[url=' . $attach['url'] . ']';
202 $attach['url'] = $attach['image'];
207 if (empty($attach['name'])) {
208 $media .= '[img]' . $attach['url'] . '[/img]';
210 $media .= '[img=' . $attach['url'] . ']' . $attach['name'] . '[/img]';
213 if (!empty($attach['image'])) {
217 if ($item['post-type'] == Item::PT_IMAGE) {
222 } elseif ($filetype == 'audio') {
223 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
227 if ($item['post-type'] == Item::PT_AUDIO) {
228 $leading .= '[audio]' . $attach['url'] . "[/audio]\n";
230 $trailing .= '[audio]' . $attach['url'] . "[/audio]\n";
232 } elseif ($filetype == 'video') {
233 if (!empty($activity['source']) && strpos($activity['source'], $attach['url'])) {
237 if ($item['post-type'] == Item::PT_VIDEO) {
238 $leading .= '[video]' . $attach['url'] . "[/video]\n";
240 $trailing .= '[video]' . $attach['url'] . "[/video]\n";
246 if (!empty($leading) && !empty(trim($item['body']))) {
247 $item['body'] = $leading . "[hr]\n" . $item['body'];
248 } elseif (!empty($leading)) {
249 $item['body'] = $leading;
252 if (!empty($trailing) && !empty(trim($item['body']))) {
253 $item['body'] = $item['body'] . "\n[hr]" . $trailing;
254 } elseif (!empty($trailing)) {
255 $item['body'] = $trailing;
264 * @param array $activity Activity array
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 public static function updateItem($activity)
269 $item = Post::selectFirst(['uri', 'uri-id', 'thr-parent', 'gravity', 'post-type'], ['uri' => $activity['id']]);
270 if (!DBA::isResult($item)) {
271 Logger::warning('No existing item, item will be created', ['uri' => $activity['id']]);
272 $item = self::createItem($activity);
273 self::postItem($activity, $item);
277 $item['changed'] = DateTimeFormat::utcNow();
278 $item['edited'] = DateTimeFormat::utc($activity['updated']);
280 $item = self::processContent($activity, $item);
282 $item = self::constructAttachList($activity, $item);
288 Item::update($item, ['uri' => $activity['id']]);
292 * Prepares data for a message
294 * @param array $activity Activity array
295 * @return array Internal item
296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 * @throws \ImagickException
299 public static function createItem($activity)
302 $item['verb'] = Activity::POST;
303 $item['thr-parent'] = $activity['reply-to-id'];
305 if ($activity['reply-to-id'] == $activity['id']) {
306 $item['gravity'] = GRAVITY_PARENT;
307 $item['object-type'] = Activity\ObjectType::NOTE;
309 $item['gravity'] = GRAVITY_COMMENT;
310 $item['object-type'] = Activity\ObjectType::COMMENT;
313 if (empty($activity['directmessage']) && ($activity['id'] != $activity['reply-to-id']) && !Post::exists(['uri' => $activity['reply-to-id']])) {
314 Logger::notice('Parent not found. Try to refetch it.', ['parent' => $activity['reply-to-id']]);
315 self::fetchMissingActivity($activity['reply-to-id'], $activity);
318 $item['diaspora_signed_text'] = $activity['diaspora:comment'] ?? '';
320 /// @todo What to do with $activity['context']?
321 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Post::exists(['uri' => $item['thr-parent']])) {
322 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
326 $item['network'] = Protocol::ACTIVITYPUB;
327 $item['author-link'] = $activity['author'];
328 $item['author-id'] = Contact::getIdForURL($activity['author']);
329 $item['owner-link'] = $activity['actor'];
330 $item['owner-id'] = Contact::getIdForURL($activity['actor']);
332 if (in_array(0, $activity['receiver']) && !empty($activity['unlisted'])) {
333 $item['private'] = Item::UNLISTED;
334 } elseif (in_array(0, $activity['receiver'])) {
335 $item['private'] = Item::PUBLIC;
337 $item['private'] = Item::PRIVATE;
340 if (!empty($activity['raw'])) {
341 $item['source'] = $activity['raw'];
342 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
343 $item['conversation-href'] = $activity['context'] ?? '';
344 $item['conversation-uri'] = $activity['conversation'] ?? '';
346 if (isset($activity['push'])) {
347 $item['direction'] = $activity['push'] ? Conversation::PUSH : Conversation::PULL;
351 if (!empty($activity['from-relay'])) {
352 $item['direction'] = Conversation::RELAY;
355 if ($activity['object_type'] == 'as:Article') {
356 $item['post-type'] = Item::PT_ARTICLE;
357 } elseif ($activity['object_type'] == 'as:Audio') {
358 $item['post-type'] = Item::PT_AUDIO;
359 } elseif ($activity['object_type'] == 'as:Document') {
360 $item['post-type'] = Item::PT_DOCUMENT;
361 } elseif ($activity['object_type'] == 'as:Event') {
362 $item['post-type'] = Item::PT_EVENT;
363 } elseif ($activity['object_type'] == 'as:Image') {
364 $item['post-type'] = Item::PT_IMAGE;
365 } elseif ($activity['object_type'] == 'as:Page') {
366 $item['post-type'] = Item::PT_PAGE;
367 } elseif ($activity['object_type'] == 'as:Video') {
368 $item['post-type'] = Item::PT_VIDEO;
370 $item['post-type'] = Item::PT_NOTE;
373 $item['isForum'] = false;
375 if (!empty($activity['thread-completion'])) {
376 if ($activity['thread-completion'] != $item['owner-id']) {
377 $actor = Contact::getById($activity['thread-completion'], ['url']);
378 $item['causer-link'] = $actor['url'];
379 $item['causer-id'] = $activity['thread-completion'];
380 Logger::info('Use inherited actor as causer.', ['id' => $item['owner-id'], 'activity' => $activity['thread-completion'], 'owner' => $item['owner-link'], 'actor' => $actor['url']]);
382 // Store the original actor in the "causer" fields to enable the check for ignored or blocked contacts
383 $item['causer-link'] = $item['owner-link'];
384 $item['causer-id'] = $item['owner-id'];
385 Logger::info('Use actor as causer.', ['id' => $item['owner-id'], 'actor' => $item['owner-link']]);
388 $item['owner-link'] = $item['author-link'];
389 $item['owner-id'] = $item['author-id'];
391 $actor = APContact::getByURL($item['owner-link'], false);
392 $item['isForum'] = ($actor['type'] == 'Group');
395 $item['uri'] = $activity['id'];
397 $item['created'] = DateTimeFormat::utc($activity['published']);
398 $item['edited'] = DateTimeFormat::utc($activity['updated']);
399 $guid = $activity['sc:identifier'] ?: self::getGUIDByURL($item['uri']);
400 $item['guid'] = $activity['diaspora:guid'] ?: $guid;
402 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
403 if (empty($item['uri-id'])) {
404 Logger::warning('Unable to get a uri-id for an item uri', ['uri' => $item['uri'], 'guid' => $item['guid']]);
408 $item = self::processContent($activity, $item);
410 Logger::info('Message was not processed');
414 $item['plink'] = $activity['alternate-url'] ?? $item['uri'];
416 $item = self::constructAttachList($activity, $item);
418 // We received the post via AP, so we set the protocol of the server to AP
419 $contact = Contact::getById($item['author-id'], ['gsid']);
420 if (!empty($contact['gsid'])) {
421 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
424 if ($item['author-id'] != $item['owner-id']) {
425 $contact = Contact::getById($item['owner-id'], ['gsid']);
426 if (!empty($contact['gsid'])) {
427 GServer::setProtocol($contact['gsid'], Post\DeliveryData::ACTIVITYPUB);
437 * @param array $activity
438 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
439 * @throws \ImagickException
441 public static function deleteItem($activity)
443 $owner = Contact::getIdForURL($activity['actor']);
445 Logger::info('Deleting item', ['object' => $activity['object_id'], 'owner' => $owner]);
446 Item::markForDeletion(['uri' => $activity['object_id'], 'owner-id' => $owner]);
450 * Prepare the item array for an activity
452 * @param array $activity Activity array
453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
454 * @throws \ImagickException
456 public static function addTag($activity)
458 if (empty($activity['object_content']) || empty($activity['object_id'])) {
462 foreach ($activity['receiver'] as $receiver) {
463 $item = Post::selectFirst(['id', 'uri-id', 'origin', 'author-link'], ['uri' => $activity['target_id'], 'uid' => $receiver]);
464 if (!DBA::isResult($item)) {
465 // We don't fetch missing content for this purpose
469 if (($item['author-link'] != $activity['actor']) && !$item['origin']) {
470 Logger::info('Not origin, not from the author, skipping update', ['id' => $item['id'], 'author' => $item['author-link'], 'actor' => $activity['actor']]);
474 Tag::store($item['uri-id'], Tag::HASHTAG, $activity['object_content'], $activity['object_id']);
475 Logger::info('Tagged item', ['id' => $item['id'], 'tag' => $activity['object_content'], 'uri' => $activity['target_id'], 'actor' => $activity['actor']]);
480 * Prepare the item array for an activity
482 * @param array $activity Activity array
483 * @param string $verb Activity verb
484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
485 * @throws \ImagickException
487 public static function createActivity($activity, $verb)
489 $item = self::createItem($activity);
490 $item['verb'] = $verb;
491 $item['thr-parent'] = $activity['object_id'];
492 $item['gravity'] = GRAVITY_ACTIVITY;
493 unset($item['post-type']);
494 $item['object-type'] = Activity\ObjectType::NOTE;
496 $item['diaspora_signed_text'] = $activity['diaspora:like'] ?? '';
498 self::postItem($activity, $item);
504 * @param array $activity Activity array
508 public static function createEvent($activity, $item)
510 $event['summary'] = HTML::toBBCode($activity['name']);
511 $event['desc'] = HTML::toBBCode($activity['content']);
512 $event['start'] = $activity['start-time'];
513 $event['finish'] = $activity['end-time'];
514 $event['nofinish'] = empty($event['finish']);
515 $event['location'] = $activity['location'];
516 $event['adjust'] = true;
517 $event['cid'] = $item['contact-id'];
518 $event['uid'] = $item['uid'];
519 $event['uri'] = $item['uri'];
520 $event['edited'] = $item['edited'];
521 $event['private'] = $item['private'];
522 $event['guid'] = $item['guid'];
523 $event['plink'] = $item['plink'];
524 $event['network'] = $item['network'];
525 $event['protocol'] = $item['protocol'];
526 $event['direction'] = $item['direction'];
527 $event['source'] = $item['source'];
529 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
530 $ev = DBA::selectFirst('event', ['id'], $condition);
531 if (DBA::isResult($ev)) {
532 $event['id'] = $ev['id'];
535 $event_id = Event::store($event);
536 Logger::info('Event was stored', ['id' => $event_id]);
540 * Process the content
542 * @param array $activity Activity array
544 * @return array|bool Returns the item array or false if there was an unexpected occurrence
547 private static function processContent($activity, $item)
549 if (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/markdown')) {
550 $item['title'] = Markdown::toBBCode($activity['name']);
551 $content = Markdown::toBBCode($activity['content']);
552 } elseif (!empty($activity['mediatype']) && ($activity['mediatype'] == 'text/bbcode')) {
553 $item['title'] = $activity['name'];
554 $content = $activity['content'];
556 // By default assume "text/html"
557 $item['title'] = HTML::toBBCode($activity['name']);
558 $content = HTML::toBBCode($activity['content']);
561 if (!empty($activity['languages'])) {
562 $item['language'] = self::processLanguages($activity['languages']);
565 if (!empty($activity['emojis'])) {
566 $content = self::replaceEmojis($content, $activity['emojis']);
569 $content = self::convertMentions($content);
571 if (!empty($activity['source'])) {
572 $item['body'] = $activity['source'];
573 $item['raw-body'] = $content;
575 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
576 $item_private = !in_array(0, $activity['item_receiver']);
577 $parent = Post::selectFirst(['id', 'uri-id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
578 if (!DBA::isResult($parent)) {
579 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
582 if ($item_private && ($parent['private'] != Item::PRIVATE)) {
583 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
587 $content = self::removeImplicitMentionsFromBody($content, $parent);
589 $item['content-warning'] = HTML::toBBCode($activity['summary']);
590 $item['raw-body'] = $item['body'] = $content;
593 self::storeFromBody($item);
594 self::storeTags($item['uri-id'], $activity['tags']);
596 $item['location'] = $activity['location'];
598 if (!empty($activity['latitude']) && !empty($activity['longitude'])) {
599 $item['coord'] = $activity['latitude'] . ' ' . $activity['longitude'];
602 $item['app'] = $activity['generator'];
608 * Store hashtags and mentions
612 private static function storeFromBody(array $item)
614 // Make sure to delete all existing tags (can happen when called via the update functionality)
615 DBA::delete('post-tag', ['uri-id' => $item['uri-id']]);
617 Tag::storeFromBody($item['uri-id'], $item['body'], '@!');
621 * Generate a GUID out of an URL
623 * @param string $url message URL
624 * @return string with GUID
626 private static function getGUIDByURL(string $url)
628 $parsed = parse_url($url);
630 $host_hash = hash('crc32', $parsed['host']);
632 unset($parsed["scheme"]);
633 unset($parsed["host"]);
635 $path = implode("/", $parsed);
637 return $host_hash . '-'. hash('fnv164', $path) . '-'. hash('joaat', $path);
641 * Creates an item post
643 * @param array $activity Activity data
644 * @param array $item item array
645 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
646 * @throws \ImagickException
648 public static function postItem(array $activity, array $item)
655 ksort($activity['receiver']);
657 foreach ($activity['receiver'] as $receiver) {
658 if ($receiver == -1) {
662 $item['uid'] = $receiver;
664 $type = $activity['reception_type'][$receiver] ?? Receiver::TARGET_UNKNOWN;
666 case Receiver::TARGET_TO:
667 $item['post-reason'] = Item::PR_TO;
669 case Receiver::TARGET_CC:
670 $item['post-reason'] = Item::PR_CC;
672 case Receiver::TARGET_BTO:
673 $item['post-reason'] = Item::PR_BTO;
675 case Receiver::TARGET_BCC:
676 $item['post-reason'] = Item::PR_BCC;
678 case Receiver::TARGET_FOLLOWER:
679 $item['post-reason'] = Item::PR_FOLLOWER;
681 case Receiver::TARGET_ANSWER:
682 $item['post-reason'] = Item::PR_COMMENT;
684 case Receiver::TARGET_GLOBAL:
685 $item['post-reason'] = Item::PR_GLOBAL;
688 $item['post-reason'] = Item::PR_NONE;
691 if (!empty($activity['from-relay'])) {
692 $item['post-reason'] = Item::PR_RELAY;
693 } elseif (!empty($activity['thread-completion'])) {
694 $item['post-reason'] = Item::PR_FETCHED;
697 if ($item['isForum'] ?? false) {
698 $item['contact-id'] = Contact::getIdForURL($activity['actor'], $receiver);
700 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver);
703 if (($receiver != 0) && empty($item['contact-id'])) {
704 $item['contact-id'] = Contact::getIdForURL($activity['author']);
707 if (!empty($activity['directmessage'])) {
708 self::postMail($activity, $item);
712 if (DI::pConfig()->get($receiver, 'system', 'accept_only_sharer', false) && ($receiver != 0) && ($item['gravity'] == GRAVITY_PARENT)) {
713 $skip = !Contact::isSharingByURL($activity['author'], $receiver);
715 if ($skip && (($activity['type'] == 'as:Announce') || ($item['isForum'] ?? false))) {
716 $skip = !Contact::isSharingByURL($activity['actor'], $receiver);
720 Logger::info('Skipping post', ['uid' => $receiver, 'url' => $item['uri']]);
724 Logger::info('Accepting post', ['uid' => $receiver, 'url' => $item['uri']]);
727 if (($item['gravity'] != GRAVITY_ACTIVITY) && ($activity['object_type'] == 'as:Event')) {
728 self::createEvent($activity, $item);
731 $item_id = Item::insert($item);
733 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
735 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
738 if ($item['uid'] == 0) {
743 // Store send a follow request for every reshare - but only when the item had been stored
744 if ($stored && ($item['private'] != Item::PRIVATE) && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
745 $author = APContact::getByURL($item['owner-link'], false);
746 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
747 if ($author['type'] != 'Group') {
748 Logger::info('Send follow request', ['uri' => $item['uri'], 'stored' => $stored, 'to' => $item['author-link']]);
749 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
755 * Store tags and mentions into the tag table
757 * @param integer $uriid
760 private static function storeTags(int $uriid, array $tags = null)
762 foreach ($tags as $tag) {
763 if (empty($tag['name']) || empty($tag['type']) || !in_array($tag['type'], ['Mention', 'Hashtag'])) {
767 $hash = substr($tag['name'], 0, 1);
769 if ($tag['type'] == 'Mention') {
770 if (in_array($hash, [Tag::TAG_CHARACTER[Tag::MENTION],
771 Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION],
772 Tag::TAG_CHARACTER[Tag::IMPLICIT_MENTION]])) {
773 $tag['name'] = substr($tag['name'], 1);
775 $type = Tag::IMPLICIT_MENTION;
777 if (!empty($tag['href'])) {
778 $apcontact = APContact::getByURL($tag['href']);
779 if (!empty($apcontact['name']) || !empty($apcontact['nick'])) {
780 $tag['name'] = $apcontact['name'] ?: $apcontact['nick'];
783 } elseif ($tag['type'] == 'Hashtag') {
784 if ($hash == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
785 $tag['name'] = substr($tag['name'], 1);
787 $type = Tag::HASHTAG;
790 if (empty($tag['name'])) {
794 Tag::store($uriid, $type, $tag['name'], $tag['href']);
799 * Creates an mail post
801 * @param array $activity Activity data
802 * @param array $item item array
803 * @return int|bool New mail table row id or false on error
804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806 private static function postMail($activity, $item)
808 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
809 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
813 Logger::info('Direct Message', $item);
816 $msg['uid'] = $item['uid'];
818 $msg['contact-id'] = $item['contact-id'];
820 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
821 $msg['from-name'] = $contact['name'];
822 $msg['from-url'] = $contact['url'];
823 $msg['from-photo'] = $contact['photo'];
825 $msg['uri'] = $item['uri'];
826 $msg['created'] = $item['created'];
828 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
829 if (DBA::isResult($parent)) {
830 $msg['parent-uri'] = $parent['parent-uri'];
831 $msg['title'] = $parent['title'];
833 $msg['parent-uri'] = $item['thr-parent'];
835 if (!empty($item['title'])) {
836 $msg['title'] = $item['title'];
837 } elseif (!empty($item['content-warning'])) {
838 $msg['title'] = $item['content-warning'];
840 // Trying to generate a title out of the body
841 $title = $item['body'];
843 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
844 $title = $matches[3];
847 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, BBCode::API, true), 0));
849 if (strlen($title) > 20) {
850 $title = substr($title, 0, 20) . '...';
853 $msg['title'] = $title;
856 $msg['body'] = $item['body'];
858 return Mail::insert($msg);
862 * Fetches missing posts
864 * @param string $url message URL
865 * @param array $child activity array with the child of this message
866 * @param string $relay_actor Relay actor
867 * @return string fetched message URL
868 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
870 public static function fetchMissingActivity(string $url, array $child = [], string $relay_actor = '')
872 if (!empty($child['receiver'])) {
873 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
878 $object = ActivityPub::fetchContent($url, $uid);
879 if (empty($object)) {
880 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
884 if (empty($object['id'])) {
885 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
889 if (!empty($object['actor'])) {
890 $object_actor = $object['actor'];
891 } elseif (!empty($object['attributedTo'])) {
892 $object_actor = $object['attributedTo'];
893 if (is_array($object_actor)) {
894 $compacted = JsonLD::compact($object);
895 $object_actor = JsonLD::fetchElement($compacted, 'as:attributedTo', '@id');
902 $signer = [$object_actor];
904 if (!empty($child['author'])) {
905 $actor = $child['author'];
908 $actor = $object_actor;
911 if (!empty($object['published'])) {
912 $published = $object['published'];
913 } elseif (!empty($child['published'])) {
914 $published = $child['published'];
916 $published = DateTimeFormat::utcNow();
920 $activity['@context'] = $object['@context'] ?? ActivityPub::CONTEXT;
921 unset($object['@context']);
922 $activity['id'] = $object['id'];
923 $activity['to'] = $object['to'] ?? [];
924 $activity['cc'] = $object['cc'] ?? [];
925 $activity['actor'] = $actor;
926 $activity['object'] = $object;
927 $activity['published'] = $published;
928 $activity['type'] = 'Create';
930 $ldactivity = JsonLD::compact($activity);
932 if (!empty($relay_actor)) {
933 $ldactivity['thread-completion'] = $ldactivity['from-relay'] = Contact::getIdForURL($relay_actor);
934 } elseif (!empty($child['thread-completion'])) {
935 $ldactivity['thread-completion'] = $child['thread-completion'];
937 $ldactivity['thread-completion'] = Contact::getIdForURL($actor);
940 if (!empty($relay_actor) && !self::acceptIncomingMessage($ldactivity, $object['id'])) {
944 ActivityPub\Receiver::processActivity($ldactivity, json_encode($activity), $uid, true, false, $signer);
946 Logger::notice('Activity had been fetched and processed.', ['url' => $url, 'object' => $activity['id']]);
948 return $activity['id'];
952 * Test if incoming relay messages should be accepted
954 * @param array $activity activity array
955 * @param string $id object ID
956 * @return boolean true if message is accepted
958 private static function acceptIncomingMessage(array $activity, string $id)
960 if (empty($activity['as:object'])) {
961 Logger::info('No object field in activity - accepted', ['id' => $id]);
965 $replyto = JsonLD::fetchElement($activity['as:object'], 'as:inReplyTo', '@id');
966 $uriid = ItemURI::getIdByURI($replyto);
967 if (Post::exists(['uri-id' => $uriid])) {
968 Logger::info('Post is a reply to an existing post - accepted', ['id' => $id, 'uri-id' => $uriid, 'replyto' => $replyto]);
972 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
973 $authorid = Contact::getIdForURL($attributed_to);
975 $body = HTML::toBBCode(JsonLD::fetchElement($activity['as:object'], 'as:content', '@value'));
978 $tags = Receiver::processTags(JsonLD::fetchElementArray($activity['as:object'], 'as:tag') ?? []);
980 foreach ($tags as $tag) {
981 if ($tag['type'] != 'Hashtag') {
984 $messageTags[] = ltrim(mb_strtolower($tag['name']), '#');
988 return Relay::isSolicitedPost($messageTags, $body, $authorid, $id, Protocol::ACTIVITYPUB);
992 * perform a "follow" request
994 * @param array $activity
995 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996 * @throws \ImagickException
998 public static function followUser($activity)
1000 $uid = User::getIdForURL($activity['object_id']);
1005 $owner = User::getOwnerDataById($uid);
1006 if (empty($owner)) {
1010 $cid = Contact::getIdForURL($activity['actor'], $uid);
1012 self::switchContact($cid);
1013 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1016 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
1017 'author-link' => $activity['actor']];
1019 // Ensure that the contact has got the right network type
1020 self::switchContact($item['author-id']);
1022 $result = Contact::addRelationship($owner, [], $item, false, $activity['content'] ?? '');
1023 if ($result === true) {
1024 ActivityPub\Transmitter::sendContactAccept($item['author-link'], $activity['id'], $owner['uid']);
1027 $cid = Contact::getIdForURL($activity['actor'], $uid);
1032 if (empty($contact)) {
1033 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
1036 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1040 * Update the given profile
1042 * @param array $activity
1043 * @throws \Exception
1045 public static function updatePerson($activity)
1047 if (empty($activity['object_id'])) {
1051 Logger::info('Updating profile', ['object' => $activity['object_id']]);
1052 Contact::updateFromProbeByURL($activity['object_id']);
1056 * Delete the given profile
1058 * @param array $activity
1059 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1061 public static function deletePerson($activity)
1063 if (empty($activity['object_id']) || empty($activity['actor'])) {
1064 Logger::info('Empty object id or actor.');
1068 if ($activity['object_id'] != $activity['actor']) {
1069 Logger::info('Object id does not match actor.');
1073 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
1074 while ($contact = DBA::fetch($contacts)) {
1075 Contact::remove($contact['id']);
1077 DBA::close($contacts);
1079 Logger::info('Deleted contact', ['object' => $activity['object_id']]);
1083 * Accept a follow request
1085 * @param array $activity
1086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1087 * @throws \ImagickException
1089 public static function acceptFollowUser($activity)
1091 $uid = User::getIdForURL($activity['object_actor']);
1096 $cid = Contact::getIdForURL($activity['actor'], $uid);
1098 Logger::info('No contact found', ['actor' => $activity['actor']]);
1102 self::switchContact($cid);
1104 $fields = ['pending' => false];
1106 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1107 if ($contact['rel'] == Contact::FOLLOWER) {
1108 $fields['rel'] = Contact::FRIEND;
1111 $condition = ['id' => $cid];
1112 DBA::update('contact', $fields, $condition);
1113 Logger::info('Accept contact request', ['contact' => $cid, 'user' => $uid]);
1117 * Reject a follow request
1119 * @param array $activity
1120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1121 * @throws \ImagickException
1123 public static function rejectFollowUser($activity)
1125 $uid = User::getIdForURL($activity['object_actor']);
1130 $cid = Contact::getIdForURL($activity['actor'], $uid);
1132 Logger::info('No contact found', ['actor' => $activity['actor']]);
1136 self::switchContact($cid);
1138 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
1139 Contact::remove($cid);
1140 Logger::info('Rejected contact request - contact removed', ['contact' => $cid, 'user' => $uid]);
1142 Logger::info('Rejected contact request', ['contact' => $cid, 'user' => $uid]);
1147 * Undo activity like "like" or "dislike"
1149 * @param array $activity
1150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1151 * @throws \ImagickException
1153 public static function undoActivity($activity)
1155 if (empty($activity['object_id'])) {
1159 if (empty($activity['object_actor'])) {
1163 $author_id = Contact::getIdForURL($activity['object_actor']);
1164 if (empty($author_id)) {
1168 Item::markForDeletion(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1172 * Activity to remove a follower
1174 * @param array $activity
1175 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1176 * @throws \ImagickException
1178 public static function undoFollowUser($activity)
1180 $uid = User::getIdForURL($activity['object_object']);
1185 $owner = User::getOwnerDataById($uid);
1186 if (empty($owner)) {
1190 $cid = Contact::getIdForURL($activity['actor'], $uid);
1192 Logger::info('No contact found', ['actor' => $activity['actor']]);
1196 self::switchContact($cid);
1198 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1199 if (!DBA::isResult($contact)) {
1203 Contact::removeFollower($owner, $contact);
1204 Logger::info('Undo following request', ['contact' => $cid, 'user' => $uid]);
1208 * Switches a contact to AP if needed
1210 * @param integer $cid Contact ID
1211 * @throws \Exception
1213 private static function switchContact($cid)
1215 $contact = DBA::selectFirst('contact', ['network', 'url'], ['id' => $cid]);
1216 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN]) || Contact::isLocal($contact['url'])) {
1220 Logger::info('Change existing contact', ['cid' => $cid, 'previous' => $contact['network']]);
1221 Contact::updateFromProbe($cid);
1225 * Collects implicit mentions like:
1226 * - the author of the parent item
1227 * - all the mentioned conversants in the parent item
1229 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
1231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1233 private static function getImplicitMentionList(array $parent)
1235 $parent_terms = Tag::getByURIId($parent['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1237 $parent_author = Contact::getByURL($parent['author-link'], false, ['url', 'nurl', 'alias']);
1239 $implicit_mentions = [];
1240 if (empty($parent_author['url'])) {
1241 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'parent-id' => $parent['id']]);
1243 $implicit_mentions[] = $parent_author['url'];
1244 $implicit_mentions[] = $parent_author['nurl'];
1245 $implicit_mentions[] = $parent_author['alias'];
1248 if (!empty($parent['alias'])) {
1249 $implicit_mentions[] = $parent['alias'];
1252 foreach ($parent_terms as $term) {
1253 $contact = Contact::getByURL($term['url'], false, ['url', 'nurl', 'alias']);
1254 if (!empty($contact['url'])) {
1255 $implicit_mentions[] = $contact['url'];
1256 $implicit_mentions[] = $contact['nurl'];
1257 $implicit_mentions[] = $contact['alias'];
1261 return $implicit_mentions;
1265 * Strips from the body prepended implicit mentions
1267 * @param string $body
1268 * @param array $parent
1271 private static function removeImplicitMentionsFromBody(string $body, array $parent)
1273 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1277 $potential_mentions = self::getImplicitMentionList($parent);
1279 $kept_mentions = [];
1281 // Extract one prepended mention at a time from the body
1282 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
1283 if (!in_array($matches[2], $potential_mentions)) {
1284 $kept_mentions[] = $matches[1];
1287 $body = $matches[3];
1290 // Re-appending the kept mentions to the body after extraction
1291 $kept_mentions[] = $body;
1293 return implode('', $kept_mentions);