3 * @file src/Protocol/ActivityPub/Processor.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Core\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Contact;
13 use Friendica\Model\APContact;
14 use Friendica\Model\Item;
15 use Friendica\Model\Event;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\JsonLD;
21 use Friendica\Util\Strings;
24 * ActivityPub Processor Protocol class
29 * Converts mentions from Pleroma into the Friendica format
33 * @return string converted body
35 private static function convertMentions($body)
37 $URLSearchString = "^\[\]";
38 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
44 * Replaces emojis in the body
46 * @param array $emojis
49 * @return string with replaced emojis
51 private static function replaceEmojis($body, array $emojis)
53 foreach ($emojis as $emoji) {
54 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
55 $body = str_replace($emoji['name'], $replace, $body);
61 * Constructs a string with tags for a given tag array
64 * @param boolean $sensitive
65 * @param array $implicit_mentions List of profile URLs to skip
66 * @return string with tags
68 private static function constructTagString(array $tags, $sensitive)
75 foreach ($tags as $tag) {
76 if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag'])) {
77 if (!empty($tag_text)) {
81 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
85 /// @todo add nsfw for $sensitive
91 * Add attachment data to the item array
93 * @param array $attachments
98 private static function constructAttachList($attachments, $item)
100 if (empty($attachments)) {
104 foreach ($attachments as $attach) {
105 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
106 if ($filetype == 'image') {
107 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
109 if (!empty($item["attach"])) {
110 $item["attach"] .= ',';
112 $item["attach"] = '';
114 if (!isset($attach['length'])) {
115 $attach['length'] = "0";
117 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
127 * @param array $activity Activity array
128 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
130 public static function updateItem($activity)
132 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
133 if (!DBA::isResult($item)) {
134 Logger::warning('Unknown item', ['uri' => $activity['id']]);
138 $item['changed'] = DateTimeFormat::utcNow();
139 $item['edited'] = $activity['updated'];
141 $item = self::processContent($activity, $item);
146 Item::update($item, ['uri' => $activity['id']]);
150 * Prepares data for a message
152 * @param array $activity Activity array
153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154 * @throws \ImagickException
156 public static function createItem($activity)
159 $item['verb'] = ACTIVITY_POST;
160 $item['thr-parent'] = $activity['reply-to-id'];
162 if ($activity['reply-to-id'] == $activity['id']) {
163 $item['gravity'] = GRAVITY_PARENT;
164 $item['object-type'] = ACTIVITY_OBJ_NOTE;
166 $item['gravity'] = GRAVITY_COMMENT;
167 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
170 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
171 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
172 self::fetchMissingActivity($activity['reply-to-id'], $activity);
175 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
177 self::postItem($activity, $item);
183 * @param array $activity
184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 * @throws \ImagickException
187 public static function deleteItem($activity)
189 $owner = Contact::getIdForURL($activity['actor']);
191 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
192 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
196 * Prepare the item array for an activity
198 * @param array $activity Activity array
199 * @param string $verb Activity verb
200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
201 * @throws \ImagickException
203 public static function createActivity($activity, $verb)
206 $item['verb'] = $verb;
207 $item['thr-parent'] = $activity['object_id'];
208 $item['gravity'] = GRAVITY_ACTIVITY;
209 $item['object-type'] = ACTIVITY_OBJ_NOTE;
211 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
213 self::postItem($activity, $item);
219 * @param array $activity Activity array
223 public static function createEvent($activity, $item)
225 $event['summary'] = HTML::toBBCode($activity['name']);
226 $event['desc'] = HTML::toBBCode($activity['content']);
227 $event['start'] = $activity['start-time'];
228 $event['finish'] = $activity['end-time'];
229 $event['nofinish'] = empty($event['finish']);
230 $event['location'] = $activity['location'];
231 $event['adjust'] = true;
232 $event['cid'] = $item['contact-id'];
233 $event['uid'] = $item['uid'];
234 $event['uri'] = $item['uri'];
235 $event['edited'] = $item['edited'];
236 $event['private'] = $item['private'];
237 $event['guid'] = $item['guid'];
238 $event['plink'] = $item['plink'];
240 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
241 $ev = DBA::selectFirst('event', ['id'], $condition);
242 if (DBA::isResult($ev)) {
243 $event['id'] = $ev['id'];
246 $event_id = Event::store($event);
247 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
251 * Process the content
253 * @param array $activity Activity array
255 * @return array|bool Returns the item array or false if there was an unexpected occurrence
258 private static function processContent($activity, $item)
260 $item['title'] = HTML::toBBCode($activity['name']);
262 if (!empty($activity['source'])) {
263 $item['body'] = $activity['source'];
265 $content = HTML::toBBCode($activity['content']);
267 if (!empty($activity['emojis'])) {
268 $content = self::replaceEmojis($content, $activity['emojis']);
271 $content = self::convertMentions($content);
273 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
274 $item_private = !in_array(0, $activity['item_receiver']);
275 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
276 if (!DBA::isResult($parent)) {
277 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
280 if ($item_private && !$parent['private']) {
281 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
285 $potential_implicit_mentions = self::getImplicitMentionList($parent);
286 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
287 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
289 $item['content-warning'] = HTML::toBBCode($activity['summary']);
290 $item['body'] = $content;
292 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
293 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
297 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
299 $item['location'] = $activity['location'];
301 if (!empty($item['latitude']) && !empty($item['longitude'])) {
302 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
305 $item['app'] = $activity['generator'];
311 * Creates an item post
313 * @param array $activity Activity data
314 * @param array $item item array
315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
316 * @throws \ImagickException
318 private static function postItem($activity, $item)
320 /// @todo What to do with $activity['context']?
322 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
323 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
327 $item['network'] = Protocol::ACTIVITYPUB;
328 $item['private'] = !in_array(0, $activity['receiver']);
329 $item['author-link'] = $activity['author'];
330 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
332 if (empty($activity['thread-completion'])) {
333 $item['owner-link'] = $activity['actor'];
334 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
336 Logger::info('Ignoring actor because of thread completion.');
337 $item['owner-link'] = $item['author-link'];
338 $item['owner-id'] = $item['author-id'];
341 $item['uri'] = $activity['id'];
343 $item['created'] = $activity['published'];
344 $item['edited'] = $activity['updated'];
345 $item['guid'] = $activity['diaspora:guid'];
347 $item = self::processContent($activity, $item);
352 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
354 $item = self::constructAttachList($activity['attachments'], $item);
358 foreach ($activity['receiver'] as $receiver) {
359 $item['uid'] = $receiver;
360 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
362 if (($receiver != 0) && empty($item['contact-id'])) {
363 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
366 if ($activity['object_type'] == 'as:Event') {
367 self::createEvent($activity, $item);
370 $item_id = Item::insert($item);
372 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
374 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
377 if ($item['uid'] == 0) {
382 // Store send a follow request for every reshare - but only when the item had been stored
383 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
384 $author = APContact::getByURL($item['owner-link'], false);
385 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
386 if ($author['type'] != 'Group') {
387 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
388 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
394 * Fetches missing posts
398 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
400 private static function fetchMissingActivity($url, $child)
402 if (Config::get('system', 'ostatus_full_threads')) {
406 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
408 $object = ActivityPub::fetchContent($url, $uid);
409 if (empty($object)) {
410 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
414 if (empty($object['id'])) {
415 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
420 $activity['@context'] = $object['@context'];
421 unset($object['@context']);
422 $activity['id'] = $object['id'];
423 $activity['to'] = defaults($object, 'to', []);
424 $activity['cc'] = defaults($object, 'cc', []);
425 $activity['actor'] = $child['author'];
426 $activity['object'] = $object;
427 $activity['published'] = defaults($object, 'published', $child['published']);
428 $activity['type'] = 'Create';
430 $ldactivity = JsonLD::compact($activity);
432 $ldactivity['thread-completion'] = true;
434 ActivityPub\Receiver::processActivity($ldactivity);
435 Logger::log('Activity ' . $url . ' had been fetched and processed.');
439 * perform a "follow" request
441 * @param array $activity
442 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
443 * @throws \ImagickException
445 public static function followUser($activity)
447 $uid = User::getIdForURL($activity['object_id']);
452 $owner = User::getOwnerDataById($uid);
454 $cid = Contact::getIdForURL($activity['actor'], $uid);
456 self::switchContact($cid);
457 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
458 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
463 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
464 'author-link' => $activity['actor']];
466 $note = Strings::escapeTags(trim(defaults($activity, 'content', '')));
468 // Ensure that the contact has got the right network type
469 self::switchContact($item['author-id']);
471 Contact::addRelationship($owner, $contact, $item, '', false, $note);
472 $cid = Contact::getIdForURL($activity['actor'], $uid);
477 if (empty($contact)) {
478 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
481 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
485 * Update the given profile
487 * @param array $activity
490 public static function updatePerson($activity)
492 if (empty($activity['object_id'])) {
496 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
497 APContact::getByURL($activity['object_id'], true);
501 * Delete the given profile
503 * @param array $activity
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 public static function deletePerson($activity)
508 if (empty($activity['object_id']) || empty($activity['actor'])) {
509 Logger::log('Empty object id or actor.', Logger::DEBUG);
513 if ($activity['object_id'] != $activity['actor']) {
514 Logger::log('Object id does not match actor.', Logger::DEBUG);
518 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
519 while ($contact = DBA::fetch($contacts)) {
520 Contact::remove($contact['id']);
522 DBA::close($contacts);
524 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
528 * Accept a follow request
530 * @param array $activity
531 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
532 * @throws \ImagickException
534 public static function acceptFollowUser($activity)
536 $uid = User::getIdForURL($activity['object_actor']);
541 $cid = Contact::getIdForURL($activity['actor'], $uid);
543 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
547 self::switchContact($cid);
549 $fields = ['pending' => false];
551 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
552 if ($contact['rel'] == Contact::FOLLOWER) {
553 $fields['rel'] = Contact::FRIEND;
556 $condition = ['id' => $cid];
557 DBA::update('contact', $fields, $condition);
558 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
562 * Reject a follow request
564 * @param array $activity
565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
566 * @throws \ImagickException
568 public static function rejectFollowUser($activity)
570 $uid = User::getIdForURL($activity['object_actor']);
575 $cid = Contact::getIdForURL($activity['actor'], $uid);
577 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
581 self::switchContact($cid);
583 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
584 Contact::remove($cid);
585 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
587 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
592 * Undo activity like "like" or "dislike"
594 * @param array $activity
595 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
596 * @throws \ImagickException
598 public static function undoActivity($activity)
600 if (empty($activity['object_id'])) {
604 if (empty($activity['object_actor'])) {
608 $author_id = Contact::getIdForURL($activity['object_actor']);
609 if (empty($author_id)) {
613 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
617 * Activity to remove a follower
619 * @param array $activity
620 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
621 * @throws \ImagickException
623 public static function undoFollowUser($activity)
625 $uid = User::getIdForURL($activity['object_object']);
630 $owner = User::getOwnerDataById($uid);
632 $cid = Contact::getIdForURL($activity['actor'], $uid);
634 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
638 self::switchContact($cid);
640 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
641 if (!DBA::isResult($contact)) {
645 Contact::removeFollower($owner, $contact);
646 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
650 * Switches a contact to AP if needed
652 * @param integer $cid Contact ID
655 private static function switchContact($cid)
657 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
658 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
662 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
663 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
667 * Collects implicit mentions like:
668 * - the author of the parent item
669 * - all the mentioned conversants in the parent item
671 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
673 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
675 private static function getImplicitMentionList(array $parent)
677 if (Config::get('system', 'disable_implicit_mentions')) {
681 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
683 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
685 $implicit_mentions = [];
686 if (empty($parent_author)) {
687 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
689 $implicit_mentions[] = $parent_author['url'];
690 $implicit_mentions[] = $parent_author['nurl'];
691 $implicit_mentions[] = $parent_author['alias'];
694 if (!empty($parent['alias'])) {
695 $implicit_mentions[] = $parent['alias'];
698 foreach ($parent_terms as $term) {
699 $contact = Contact::getDetailsByURL($term['url'], 0);
700 if (!empty($contact)) {
701 $implicit_mentions[] = $contact['url'];
702 $implicit_mentions[] = $contact['nurl'];
703 $implicit_mentions[] = $contact['alias'];
707 return $implicit_mentions;
711 * Strips from the body prepended implicit mentions
713 * @param string $body
714 * @param array $potential_mentions
717 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
719 if (Config::get('system', 'disable_implicit_mentions')) {
725 // Extract one prepended mention at a time from the body
726 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
727 if (!in_array($matches[2], $potential_mentions) ) {
728 $kept_mentions[] = $matches[1];
734 // Re-appending the kept mentions to the body after extraction
735 $kept_mentions[] = $body;
737 return implode('', $kept_mentions);
740 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
742 if (Config::get('system', 'disable_implicit_mentions')) {
743 return $activity_tags;
746 foreach ($activity_tags as $index => $tag) {
747 if (in_array($tag['href'], $potential_mentions)) {
748 $activity_tags[$index]['name'] = preg_replace(
749 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
750 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
751 $activity_tags[$index]['name'],
757 return $activity_tags;