3 * @file src/Protocol/ActivityPub/Processor.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Content\Text\HTML;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Contact;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Event;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Model\Mail;
20 use Friendica\Protocol\ActivityPub;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\JsonLD;
23 use Friendica\Util\Strings;
26 * ActivityPub Processor Protocol class
31 * Converts mentions from Pleroma into the Friendica format
35 * @return string converted body
37 private static function convertMentions($body)
39 $URLSearchString = "^\[\]";
40 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
46 * Replaces emojis in the body
48 * @param array $emojis
51 * @return string with replaced emojis
53 private static function replaceEmojis($body, array $emojis)
55 foreach ($emojis as $emoji) {
56 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
57 $body = str_replace($emoji['name'], $replace, $body);
63 * Constructs a string with tags for a given tag array
66 * @param boolean $sensitive
67 * @param array $implicit_mentions List of profile URLs to skip
68 * @return string with tags
70 private static function constructTagString(array $tags, $sensitive)
77 foreach ($tags as $tag) {
78 if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag'])) {
79 if (!empty($tag_text)) {
83 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
87 /// @todo add nsfw for $sensitive
93 * Add attachment data to the item array
95 * @param array $attachments
97 * @param boolean $no_images
101 private static function constructAttachList($attachments, $item, $no_images)
103 if (empty($attachments)) {
107 foreach ($attachments as $attach) {
108 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
109 if ($filetype == 'image') {
114 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
116 if (!empty($item["attach"])) {
117 $item["attach"] .= ',';
119 $item["attach"] = '';
121 if (!isset($attach['length'])) {
122 $attach['length'] = "0";
124 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
134 * @param array $activity Activity array
135 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
137 public static function updateItem($activity)
139 $item = Item::selectFirst(['uri', 'thr-parent', 'gravity'], ['uri' => $activity['id']]);
140 if (!DBA::isResult($item)) {
141 Logger::warning('Unknown item', ['uri' => $activity['id']]);
145 $item['changed'] = DateTimeFormat::utcNow();
146 $item['edited'] = $activity['updated'];
148 $item = self::processContent($activity, $item);
153 Item::update($item, ['uri' => $activity['id']]);
157 * Prepares data for a message
159 * @param array $activity Activity array
160 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
161 * @throws \ImagickException
163 public static function createItem($activity)
166 $item['verb'] = ACTIVITY_POST;
167 $item['thr-parent'] = $activity['reply-to-id'];
169 if ($activity['reply-to-id'] == $activity['id']) {
170 $item['gravity'] = GRAVITY_PARENT;
171 $item['object-type'] = ACTIVITY_OBJ_NOTE;
173 $item['gravity'] = GRAVITY_COMMENT;
174 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
177 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
178 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
179 self::fetchMissingActivity($activity['reply-to-id'], $activity);
182 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
184 self::postItem($activity, $item);
190 * @param array $activity
191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
192 * @throws \ImagickException
194 public static function deleteItem($activity)
196 $owner = Contact::getIdForURL($activity['actor']);
198 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
199 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
203 * Prepare the item array for an activity
205 * @param array $activity Activity array
206 * @param string $verb Activity verb
207 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
208 * @throws \ImagickException
210 public static function createActivity($activity, $verb)
213 $item['verb'] = $verb;
214 $item['thr-parent'] = $activity['object_id'];
215 $item['gravity'] = GRAVITY_ACTIVITY;
216 $item['object-type'] = ACTIVITY_OBJ_NOTE;
218 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
220 self::postItem($activity, $item);
226 * @param array $activity Activity array
230 public static function createEvent($activity, $item)
232 $event['summary'] = HTML::toBBCode($activity['name']);
233 $event['desc'] = HTML::toBBCode($activity['content']);
234 $event['start'] = $activity['start-time'];
235 $event['finish'] = $activity['end-time'];
236 $event['nofinish'] = empty($event['finish']);
237 $event['location'] = $activity['location'];
238 $event['adjust'] = true;
239 $event['cid'] = $item['contact-id'];
240 $event['uid'] = $item['uid'];
241 $event['uri'] = $item['uri'];
242 $event['edited'] = $item['edited'];
243 $event['private'] = $item['private'];
244 $event['guid'] = $item['guid'];
245 $event['plink'] = $item['plink'];
247 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
248 $ev = DBA::selectFirst('event', ['id'], $condition);
249 if (DBA::isResult($ev)) {
250 $event['id'] = $ev['id'];
253 $event_id = Event::store($event);
254 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
258 * Process the content
260 * @param array $activity Activity array
262 * @return array|bool Returns the item array or false if there was an unexpected occurrence
265 private static function processContent($activity, $item)
267 $item['title'] = HTML::toBBCode($activity['name']);
269 if (!empty($activity['source'])) {
270 $item['body'] = $activity['source'];
272 $content = HTML::toBBCode($activity['content']);
274 if (!empty($activity['emojis'])) {
275 $content = self::replaceEmojis($content, $activity['emojis']);
278 $content = self::convertMentions($content);
280 if (empty($activity['directmessage']) && ($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
281 $item_private = !in_array(0, $activity['item_receiver']);
282 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
283 if (!DBA::isResult($parent)) {
284 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
287 if ($item_private && !$parent['private']) {
288 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
292 $potential_implicit_mentions = self::getImplicitMentionList($parent);
293 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
294 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
296 $item['content-warning'] = HTML::toBBCode($activity['summary']);
297 $item['body'] = $content;
299 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
300 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
304 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
306 $item['location'] = $activity['location'];
308 if (!empty($item['latitude']) && !empty($item['longitude'])) {
309 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
312 $item['app'] = $activity['generator'];
318 * Creates an item post
320 * @param array $activity Activity data
321 * @param array $item item array
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
323 * @throws \ImagickException
325 private static function postItem($activity, $item)
327 /// @todo What to do with $activity['context']?
328 if (empty($activity['directmessage']) && ($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
329 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
333 $item['network'] = Protocol::ACTIVITYPUB;
334 $item['private'] = !in_array(0, $activity['receiver']);
335 $item['author-link'] = $activity['author'];
336 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
338 if (empty($activity['thread-completion'])) {
339 $item['owner-link'] = $activity['actor'];
340 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
342 Logger::info('Ignoring actor because of thread completion.');
343 $item['owner-link'] = $item['author-link'];
344 $item['owner-id'] = $item['author-id'];
347 $item['uri'] = $activity['id'];
349 $item['created'] = $activity['published'];
350 $item['edited'] = $activity['updated'];
351 $item['guid'] = $activity['diaspora:guid'];
353 $item = self::processContent($activity, $item);
358 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
360 $item = self::constructAttachList($activity['attachments'], $item, !empty($activity['source']));
364 foreach ($activity['receiver'] as $receiver) {
365 $item['uid'] = $receiver;
366 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
368 if (($receiver != 0) && empty($item['contact-id'])) {
369 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
372 if (!empty($activity['directmessage'])) {
373 self::postMail($activity, $item);
377 if ($activity['object_type'] == 'as:Event') {
378 self::createEvent($activity, $item);
381 $item_id = Item::insert($item);
383 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
385 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
388 if ($item['uid'] == 0) {
393 // Store send a follow request for every reshare - but only when the item had been stored
394 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
395 $author = APContact::getByURL($item['owner-link'], false);
396 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
397 if ($author['type'] != 'Group') {
398 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
399 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
405 * Creates an mail post
407 * @param array $activity Activity data
408 * @param array $item item array
409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
410 * @throws \ImagickException
412 private static function postMail($activity, $item)
414 if (($item['gravity'] != GRAVITY_PARENT) && !DBA::exists('mail', ['uri' => $item['thr-parent'], 'uid' => $item['uid']])) {
415 Logger::info('Parent not found, mail will be discarded.', ['uid' => $item['uid'], 'uri' => $item['thr-parent']]);
419 Logger::info('Direct Message', $item);
422 $msg['uid'] = $item['uid'];
424 $msg['contact-id'] = $item['contact-id'];
426 $contact = Contact::getById($item['contact-id'], ['name', 'url', 'photo']);
427 $msg['from-name'] = $contact['name'];
428 $msg['from-url'] = $contact['url'];
429 $msg['from-photo'] = $contact['photo'];
431 $msg['uri'] = $item['uri'];
432 $msg['created'] = $item['created'];
434 $parent = DBA::selectFirst('mail', ['parent-uri', 'title'], ['uri' => $item['thr-parent']]);
435 if (DBA::isResult($parent)) {
436 $msg['parent-uri'] = $parent['parent-uri'];
437 $msg['title'] = $parent['title'];
439 $msg['parent-uri'] = $item['thr-parent'];
441 if (!empty($item['title'])) {
442 $msg['title'] = $item['title'];
443 } elseif (!empty($item['content-warning'])) {
444 $msg['title'] = $item['content-warning'];
446 // Trying to generate a title out of the body
447 $title = $item['body'];
449 while (preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $title, $matches)) {
450 $title = $matches[3];
453 $title = trim(HTML::toPlaintext(BBCode::convert($title, false, 2, true), 0));
455 if (strlen($title) > 20) {
456 $title = substr($title, 0, 20) . '...';
459 $msg['title'] = $title;
462 $msg['body'] = $item['body'];
468 * Fetches missing posts
472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
474 private static function fetchMissingActivity($url, $child)
476 if (Config::get('system', 'ostatus_full_threads')) {
480 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
482 $object = ActivityPub::fetchContent($url, $uid);
483 if (empty($object)) {
484 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
488 if (empty($object['id'])) {
489 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
494 $activity['@context'] = $object['@context'];
495 unset($object['@context']);
496 $activity['id'] = $object['id'];
497 $activity['to'] = defaults($object, 'to', []);
498 $activity['cc'] = defaults($object, 'cc', []);
499 $activity['actor'] = $child['author'];
500 $activity['object'] = $object;
501 $activity['published'] = defaults($object, 'published', $child['published']);
502 $activity['type'] = 'Create';
504 $ldactivity = JsonLD::compact($activity);
506 $ldactivity['thread-completion'] = true;
508 ActivityPub\Receiver::processActivity($ldactivity);
509 Logger::log('Activity ' . $url . ' had been fetched and processed.');
513 * perform a "follow" request
515 * @param array $activity
516 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
517 * @throws \ImagickException
519 public static function followUser($activity)
521 $uid = User::getIdForURL($activity['object_id']);
526 $owner = User::getOwnerDataById($uid);
528 $cid = Contact::getIdForURL($activity['actor'], $uid);
530 self::switchContact($cid);
531 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
532 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
537 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
538 'author-link' => $activity['actor']];
540 $note = Strings::escapeTags(trim(defaults($activity, 'content', '')));
542 // Ensure that the contact has got the right network type
543 self::switchContact($item['author-id']);
545 Contact::addRelationship($owner, $contact, $item, '', false, $note);
546 $cid = Contact::getIdForURL($activity['actor'], $uid);
551 if (empty($contact)) {
552 DBA::update('contact', ['hub-verify' => $activity['id'], 'protocol' => Protocol::ACTIVITYPUB], ['id' => $cid]);
555 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
559 * Update the given profile
561 * @param array $activity
564 public static function updatePerson($activity)
566 if (empty($activity['object_id'])) {
570 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
571 APContact::getByURL($activity['object_id'], true);
575 * Delete the given profile
577 * @param array $activity
578 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
580 public static function deletePerson($activity)
582 if (empty($activity['object_id']) || empty($activity['actor'])) {
583 Logger::log('Empty object id or actor.', Logger::DEBUG);
587 if ($activity['object_id'] != $activity['actor']) {
588 Logger::log('Object id does not match actor.', Logger::DEBUG);
592 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
593 while ($contact = DBA::fetch($contacts)) {
594 Contact::remove($contact['id']);
596 DBA::close($contacts);
598 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
602 * Accept a follow request
604 * @param array $activity
605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606 * @throws \ImagickException
608 public static function acceptFollowUser($activity)
610 $uid = User::getIdForURL($activity['object_actor']);
615 $cid = Contact::getIdForURL($activity['actor'], $uid);
617 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
621 self::switchContact($cid);
623 $fields = ['pending' => false];
625 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
626 if ($contact['rel'] == Contact::FOLLOWER) {
627 $fields['rel'] = Contact::FRIEND;
630 $condition = ['id' => $cid];
631 DBA::update('contact', $fields, $condition);
632 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
636 * Reject a follow request
638 * @param array $activity
639 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
640 * @throws \ImagickException
642 public static function rejectFollowUser($activity)
644 $uid = User::getIdForURL($activity['object_actor']);
649 $cid = Contact::getIdForURL($activity['actor'], $uid);
651 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
655 self::switchContact($cid);
657 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING])) {
658 Contact::remove($cid);
659 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
661 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
666 * Undo activity like "like" or "dislike"
668 * @param array $activity
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670 * @throws \ImagickException
672 public static function undoActivity($activity)
674 if (empty($activity['object_id'])) {
678 if (empty($activity['object_actor'])) {
682 $author_id = Contact::getIdForURL($activity['object_actor']);
683 if (empty($author_id)) {
687 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
691 * Activity to remove a follower
693 * @param array $activity
694 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
695 * @throws \ImagickException
697 public static function undoFollowUser($activity)
699 $uid = User::getIdForURL($activity['object_object']);
704 $owner = User::getOwnerDataById($uid);
706 $cid = Contact::getIdForURL($activity['actor'], $uid);
708 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
712 self::switchContact($cid);
714 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
715 if (!DBA::isResult($contact)) {
719 Contact::removeFollower($owner, $contact);
720 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
724 * Switches a contact to AP if needed
726 * @param integer $cid Contact ID
729 private static function switchContact($cid)
731 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
732 if (!DBA::isResult($contact) || in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
736 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
737 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
741 * Collects implicit mentions like:
742 * - the author of the parent item
743 * - all the mentioned conversants in the parent item
745 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
749 private static function getImplicitMentionList(array $parent)
751 if (Config::get('system', 'disable_implicit_mentions')) {
755 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
757 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
759 $implicit_mentions = [];
760 if (empty($parent_author)) {
761 Logger::notice('Author public contact unknown.', ['author-link' => $parent['author-link'], 'item-id' => $parent['id']]);
763 $implicit_mentions[] = $parent_author['url'];
764 $implicit_mentions[] = $parent_author['nurl'];
765 $implicit_mentions[] = $parent_author['alias'];
768 if (!empty($parent['alias'])) {
769 $implicit_mentions[] = $parent['alias'];
772 foreach ($parent_terms as $term) {
773 $contact = Contact::getDetailsByURL($term['url'], 0);
774 if (!empty($contact)) {
775 $implicit_mentions[] = $contact['url'];
776 $implicit_mentions[] = $contact['nurl'];
777 $implicit_mentions[] = $contact['alias'];
781 return $implicit_mentions;
785 * Strips from the body prepended implicit mentions
787 * @param string $body
788 * @param array $potential_mentions
791 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
793 if (Config::get('system', 'disable_implicit_mentions')) {
799 // Extract one prepended mention at a time from the body
800 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#is', $body, $matches)) {
801 if (!in_array($matches[2], $potential_mentions) ) {
802 $kept_mentions[] = $matches[1];
808 // Re-appending the kept mentions to the body after extraction
809 $kept_mentions[] = $body;
811 return implode('', $kept_mentions);
814 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
816 if (Config::get('system', 'disable_implicit_mentions')) {
817 return $activity_tags;
820 foreach ($activity_tags as $index => $tag) {
821 if (in_array($tag['href'], $potential_mentions)) {
822 $activity_tags[$index]['name'] = preg_replace(
823 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
824 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
825 $activity_tags[$index]['name'],
831 return $activity_tags;