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
95 * @param boolean $no_images
99 private static function constructAttachList($attachments, $item, $no_images)
101 if (empty($attachments)) {
105 foreach ($attachments as $attach) {
106 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
107 if ($filetype == 'image') {
112 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
114 if (!empty($item["attach"])) {
115 $item["attach"] .= ',';
117 $item["attach"] = '';
119 if (!isset($attach['length'])) {
120 $attach['length'] = "0";
122 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
132 * @param array $activity Activity array
133 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
135 public static function updateItem($activity)
137 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
138 if (!DBA::isResult($item)) {
139 Logger::warning('Unknown item', ['uri' => $activity['id']]);
143 $item['changed'] = DateTimeFormat::utcNow();
144 $item['edited'] = $activity['updated'];
146 $item = self::processContent($activity, $item);
151 Item::update($item, ['uri' => $activity['id']]);
155 * Prepares data for a message
157 * @param array $activity Activity array
158 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
159 * @throws \ImagickException
161 public static function createItem($activity)
164 $item['verb'] = ACTIVITY_POST;
165 $item['thr-parent'] = $activity['reply-to-id'];
167 if ($activity['reply-to-id'] == $activity['id']) {
168 $item['gravity'] = GRAVITY_PARENT;
169 $item['object-type'] = ACTIVITY_OBJ_NOTE;
171 $item['gravity'] = GRAVITY_COMMENT;
172 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
175 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
176 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
177 self::fetchMissingActivity($activity['reply-to-id'], $activity);
180 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
182 self::postItem($activity, $item);
188 * @param array $activity
189 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
190 * @throws \ImagickException
192 public static function deleteItem($activity)
194 $owner = Contact::getIdForURL($activity['actor']);
196 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
197 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
201 * Prepare the item array for an activity
203 * @param array $activity Activity array
204 * @param string $verb Activity verb
205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
206 * @throws \ImagickException
208 public static function createActivity($activity, $verb)
211 $item['verb'] = $verb;
212 $item['thr-parent'] = $activity['object_id'];
213 $item['gravity'] = GRAVITY_ACTIVITY;
214 $item['object-type'] = ACTIVITY_OBJ_NOTE;
216 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
218 self::postItem($activity, $item);
224 * @param array $activity Activity array
228 public static function createEvent($activity, $item)
230 $event['summary'] = HTML::toBBCode($activity['name']);
231 $event['desc'] = HTML::toBBCode($activity['content']);
232 $event['start'] = $activity['start-time'];
233 $event['finish'] = $activity['end-time'];
234 $event['nofinish'] = empty($event['finish']);
235 $event['location'] = $activity['location'];
236 $event['adjust'] = true;
237 $event['cid'] = $item['contact-id'];
238 $event['uid'] = $item['uid'];
239 $event['uri'] = $item['uri'];
240 $event['edited'] = $item['edited'];
241 $event['private'] = $item['private'];
242 $event['guid'] = $item['guid'];
243 $event['plink'] = $item['plink'];
245 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
246 $ev = DBA::selectFirst('event', ['id'], $condition);
247 if (DBA::isResult($ev)) {
248 $event['id'] = $ev['id'];
251 $event_id = Event::store($event);
252 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
256 * Process the content
258 * @param array $activity Activity array
260 * @return array|bool Returns the item array or false if there was an unexpected occurrence
263 private static function processContent($activity, $item)
265 $item['title'] = HTML::toBBCode($activity['name']);
267 if (!empty($activity['source'])) {
268 $item['body'] = $activity['source'];
270 $content = HTML::toBBCode($activity['content']);
272 if (!empty($activity['emojis'])) {
273 $content = self::replaceEmojis($content, $activity['emojis']);
276 $content = self::convertMentions($content);
278 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
279 $item_private = !in_array(0, $activity['item_receiver']);
280 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
281 if (!DBA::isResult($parent)) {
282 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
285 if ($item_private && !$parent['private']) {
286 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
290 $potential_implicit_mentions = self::getImplicitMentionList($parent);
291 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
292 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
294 $item['content-warning'] = HTML::toBBCode($activity['summary']);
295 $item['body'] = $content;
297 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
298 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
302 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
304 $item['location'] = $activity['location'];
306 if (!empty($item['latitude']) && !empty($item['longitude'])) {
307 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
310 $item['app'] = $activity['generator'];
316 * Creates an item post
318 * @param array $activity Activity data
319 * @param array $item item array
320 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 * @throws \ImagickException
323 private static function postItem($activity, $item)
325 /// @todo What to do with $activity['context']?
327 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
328 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
332 $item['network'] = Protocol::ACTIVITYPUB;
333 $item['private'] = !in_array(0, $activity['receiver']);
334 $item['author-link'] = $activity['author'];
335 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
337 if (empty($activity['thread-completion'])) {
338 $item['owner-link'] = $activity['actor'];
339 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
341 Logger::info('Ignoring actor because of thread completion.');
342 $item['owner-link'] = $item['author-link'];
343 $item['owner-id'] = $item['author-id'];
346 $item['uri'] = $activity['id'];
348 $item['created'] = $activity['published'];
349 $item['edited'] = $activity['updated'];
350 $item['guid'] = $activity['diaspora:guid'];
352 $item = self::processContent($activity, $item);
357 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
359 $item = self::constructAttachList($activity['attachments'], $item, !empty($activity['source']));
363 foreach ($activity['receiver'] as $receiver) {
364 $item['uid'] = $receiver;
365 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
367 if (($receiver != 0) && empty($item['contact-id'])) {
368 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
371 if ($activity['object_type'] == 'as:Event') {
372 self::createEvent($activity, $item);
375 $item_id = Item::insert($item);
377 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
379 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
382 if ($item['uid'] == 0) {
387 // Store send a follow request for every reshare - but only when the item had been stored
388 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
389 $author = APContact::getByURL($item['owner-link'], false);
390 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
391 if ($author['type'] != 'Group') {
392 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
393 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
399 * Fetches missing posts
403 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
405 private static function fetchMissingActivity($url, $child)
407 if (Config::get('system', 'ostatus_full_threads')) {
411 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
413 $object = ActivityPub::fetchContent($url, $uid);
414 if (empty($object)) {
415 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
419 if (empty($object['id'])) {
420 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
425 $activity['@context'] = $object['@context'];
426 unset($object['@context']);
427 $activity['id'] = $object['id'];
428 $activity['to'] = defaults($object, 'to', []);
429 $activity['cc'] = defaults($object, 'cc', []);
430 $activity['actor'] = $child['author'];
431 $activity['object'] = $object;
432 $activity['published'] = defaults($object, 'published', $child['published']);
433 $activity['type'] = 'Create';
435 $ldactivity = JsonLD::compact($activity);
437 $ldactivity['thread-completion'] = true;
439 ActivityPub\Receiver::processActivity($ldactivity);
440 Logger::log('Activity ' . $url . ' had been fetched and processed.');
444 * perform a "follow" request
446 * @param array $activity
447 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
448 * @throws \ImagickException
450 public static function followUser($activity)
452 $uid = User::getIdForURL($activity['object_id']);
457 $owner = User::getOwnerDataById($uid);
459 $cid = Contact::getIdForURL($activity['actor'], $uid);
461 self::switchContact($cid);
462 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
463 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
468 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
469 'author-link' => $activity['actor']];
471 $note = Strings::escapeTags(trim(defaults($activity, 'content', '')));
473 // Ensure that the contact has got the right network type
474 self::switchContact($item['author-id']);
476 Contact::addRelationship($owner, $contact, $item, '', false, $note);
477 $cid = Contact::getIdForURL($activity['actor'], $uid);
482 if (empty($contact)) {
483 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
486 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
490 * Update the given profile
492 * @param array $activity
495 public static function updatePerson($activity)
497 if (empty($activity['object_id'])) {
501 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
502 APContact::getByURL($activity['object_id'], true);
506 * Delete the given profile
508 * @param array $activity
509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
511 public static function deletePerson($activity)
513 if (empty($activity['object_id']) || empty($activity['actor'])) {
514 Logger::log('Empty object id or actor.', Logger::DEBUG);
518 if ($activity['object_id'] != $activity['actor']) {
519 Logger::log('Object id does not match actor.', Logger::DEBUG);
523 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
524 while ($contact = DBA::fetch($contacts)) {
525 Contact::remove($contact['id']);
527 DBA::close($contacts);
529 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
533 * Accept a follow request
535 * @param array $activity
536 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
537 * @throws \ImagickException
539 public static function acceptFollowUser($activity)
541 $uid = User::getIdForURL($activity['object_actor']);
546 $cid = Contact::getIdForURL($activity['actor'], $uid);
548 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
552 self::switchContact($cid);
554 $fields = ['pending' => false];
556 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
557 if ($contact['rel'] == Contact::FOLLOWER) {
558 $fields['rel'] = Contact::FRIEND;
561 $condition = ['id' => $cid];
562 DBA::update('contact', $fields, $condition);
563 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
567 * Reject a follow request
569 * @param array $activity
570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
571 * @throws \ImagickException
573 public static function rejectFollowUser($activity)
575 $uid = User::getIdForURL($activity['object_actor']);
580 $cid = Contact::getIdForURL($activity['actor'], $uid);
582 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
586 self::switchContact($cid);
588 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
589 Contact::remove($cid);
590 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
592 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
597 * Undo activity like "like" or "dislike"
599 * @param array $activity
600 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
601 * @throws \ImagickException
603 public static function undoActivity($activity)
605 if (empty($activity['object_id'])) {
609 if (empty($activity['object_actor'])) {
613 $author_id = Contact::getIdForURL($activity['object_actor']);
614 if (empty($author_id)) {
618 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
622 * Activity to remove a follower
624 * @param array $activity
625 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
626 * @throws \ImagickException
628 public static function undoFollowUser($activity)
630 $uid = User::getIdForURL($activity['object_object']);
635 $owner = User::getOwnerDataById($uid);
637 $cid = Contact::getIdForURL($activity['actor'], $uid);
639 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
643 self::switchContact($cid);
645 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
646 if (!DBA::isResult($contact)) {
650 Contact::removeFollower($owner, $contact);
651 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
655 * Switches a contact to AP if needed
657 * @param integer $cid Contact ID
660 private static function switchContact($cid)
662 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
663 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
667 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
668 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
672 * Collects implicit mentions like:
673 * - the author of the parent item
674 * - all the mentioned conversants in the parent item
676 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
680 private static function getImplicitMentionList(array $parent)
682 if (Config::get('system', 'disable_implicit_mentions')) {
686 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
688 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
690 $implicit_mentions = [];
691 if (empty($parent_author)) {
692 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
694 $implicit_mentions[] = $parent_author['url'];
695 $implicit_mentions[] = $parent_author['nurl'];
696 $implicit_mentions[] = $parent_author['alias'];
699 if (!empty($parent['alias'])) {
700 $implicit_mentions[] = $parent['alias'];
703 foreach ($parent_terms as $term) {
704 $contact = Contact::getDetailsByURL($term['url'], 0);
705 if (!empty($contact)) {
706 $implicit_mentions[] = $contact['url'];
707 $implicit_mentions[] = $contact['nurl'];
708 $implicit_mentions[] = $contact['alias'];
712 return $implicit_mentions;
716 * Strips from the body prepended implicit mentions
718 * @param string $body
719 * @param array $potential_mentions
722 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
724 if (Config::get('system', 'disable_implicit_mentions')) {
730 // Extract one prepended mention at a time from the body
731 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
732 if (!in_array($matches[2], $potential_mentions) ) {
733 $kept_mentions[] = $matches[1];
739 // Re-appending the kept mentions to the body after extraction
740 $kept_mentions[] = $body;
742 return implode('', $kept_mentions);
745 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
747 if (Config::get('system', 'disable_implicit_mentions')) {
748 return $activity_tags;
751 foreach ($activity_tags as $index => $tag) {
752 if (in_array($tag['href'], $potential_mentions)) {
753 $activity_tags[$index]['name'] = preg_replace(
754 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
755 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
756 $activity_tags[$index]['name'],
762 return $activity_tags;