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 public 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'];
140 $item['title'] = HTML::toBBCode($activity['name']);
141 $item['content-warning'] = HTML::toBBCode($activity['summary']);
143 $content = HTML::toBBCode($activity['content']);
144 $content = self::replaceEmojis($content, $activity['emojis']);
145 $content = self::convertMentions($content);
147 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
148 $parent = Item::selectFirst(['id', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
149 if (!DBA::isResult($parent)) {
150 Logger::warning('Unknown parent item.', ['uri' => $item['thr-parent']]);
154 $potential_implicit_mentions = self::getImplicitMentionList($parent);
155 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
156 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
159 $item['body'] = $content;
160 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
162 Item::update($item, ['uri' => $activity['id']]);
166 * Prepares data for a message
168 * @param array $activity Activity array
169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
170 * @throws \ImagickException
172 public static function createItem($activity)
175 $item['verb'] = ACTIVITY_POST;
176 $item['thr-parent'] = $activity['reply-to-id'];
178 if ($activity['reply-to-id'] == $activity['id']) {
179 $item['gravity'] = GRAVITY_PARENT;
180 $item['object-type'] = ACTIVITY_OBJ_NOTE;
182 $item['gravity'] = GRAVITY_COMMENT;
183 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
186 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
187 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
188 self::fetchMissingActivity($activity['reply-to-id'], $activity);
191 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
193 self::postItem($activity, $item);
199 * @param array $activity
200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
201 * @throws \ImagickException
203 public static function deleteItem($activity)
205 $owner = Contact::getIdForURL($activity['actor']);
207 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
208 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
212 * Prepare the item array for an activity
214 * @param array $activity Activity array
215 * @param string $verb Activity verb
216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217 * @throws \ImagickException
219 public static function createActivity($activity, $verb)
222 $item['verb'] = $verb;
223 $item['thr-parent'] = $activity['object_id'];
224 $item['gravity'] = GRAVITY_ACTIVITY;
225 $item['object-type'] = ACTIVITY_OBJ_NOTE;
227 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
229 self::postItem($activity, $item);
235 * @param array $activity Activity array
239 public static function createEvent($activity, $item)
241 $event['summary'] = HTML::toBBCode($activity['name']);
242 $event['desc'] = HTML::toBBCode($activity['content']);
243 $event['start'] = $activity['start-time'];
244 $event['finish'] = $activity['end-time'];
245 $event['nofinish'] = empty($event['finish']);
246 $event['location'] = $activity['location'];
247 $event['adjust'] = true;
248 $event['cid'] = $item['contact-id'];
249 $event['uid'] = $item['uid'];
250 $event['uri'] = $item['uri'];
251 $event['edited'] = $item['edited'];
252 $event['private'] = $item['private'];
253 $event['guid'] = $item['guid'];
254 $event['plink'] = $item['plink'];
256 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
257 $ev = DBA::selectFirst('event', ['id'], $condition);
258 if (DBA::isResult($ev)) {
259 $event['id'] = $ev['id'];
262 $event_id = Event::store($event);
263 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
267 * Creates an item post
269 * @param array $activity Activity data
270 * @param array $item item array
271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 * @throws \ImagickException
274 private static function postItem($activity, $item)
276 /// @todo What to do with $activity['context']?
278 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['thr-parent']])) {
279 Logger::info('Parent not found, message will be discarded.', ['thr-parent' => $item['thr-parent']]);
283 $item['network'] = Protocol::ACTIVITYPUB;
284 $item['private'] = !in_array(0, $activity['receiver']);
285 $item['author-link'] = $activity['author'];
286 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
288 if (empty($activity['thread-completion'])) {
289 $item['owner-link'] = $activity['actor'];
290 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
292 Logger::info('Ignoring actor because of thread completion.');
293 $item['owner-link'] = $item['author-link'];
294 $item['owner-id'] = $item['author-id'];
297 $item['uri'] = $activity['id'];
298 $content = HTML::toBBCode($activity['content']);
299 $content = self::replaceEmojis($content, $activity['emojis']);
300 $content = self::convertMentions($content);
302 if (($item['thr-parent'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
303 $item_private = !in_array(0, $activity['item_receiver']);
304 $parent = Item::selectFirst(['id', 'private', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
305 if (!DBA::isResult($parent)) {
308 if ($item_private && !$parent['private']) {
309 Logger::warning('Item is private but the parent is not. Dropping.', ['item-uri' => $item['uri'], 'thr-parent' => $item['thr-parent']]);
313 $potential_implicit_mentions = self::getImplicitMentionList($parent);
314 $content = self::removeImplicitMentionsFromBody($content, $potential_implicit_mentions);
315 $activity['tags'] = self::convertImplicitMentionsInTags($activity['tags'], $potential_implicit_mentions);
318 $item['created'] = $activity['published'];
319 $item['edited'] = $activity['updated'];
320 $item['guid'] = $activity['diaspora:guid'];
321 $item['title'] = HTML::toBBCode($activity['name']);
322 $item['content-warning'] = HTML::toBBCode($activity['summary']);
323 $item['body'] = $content;
325 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
326 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
329 $item['location'] = $activity['location'];
331 if (!empty($item['latitude']) && !empty($item['longitude'])) {
332 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
335 $item['tag'] = self::constructTagString($activity['tags'], $activity['sensitive']);
336 $item['app'] = $activity['generator'];
337 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
339 $item = self::constructAttachList($activity['attachments'], $item);
341 if (!empty($activity['source'])) {
342 $item['body'] = $activity['source'];
347 foreach ($activity['receiver'] as $receiver) {
348 $item['uid'] = $receiver;
349 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
351 if (($receiver != 0) && empty($item['contact-id'])) {
352 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
355 if ($activity['object_type'] == 'as:Event') {
356 self::createEvent($activity, $item);
359 $item_id = Item::insert($item);
361 Logger::info('Item insertion successful', ['user' => $item['uid'], 'item_id' => $item_id]);
363 Logger::notice('Item insertion aborted', ['user' => $item['uid']]);
366 if ($item['uid'] == 0) {
371 // Store send a follow request for every reshare - but only when the item had been stored
372 if ($stored && !$item['private'] && ($item['gravity'] == GRAVITY_PARENT) && ($item['author-link'] != $item['owner-link'])) {
373 $author = APContact::getByURL($item['owner-link'], false);
374 // We send automatic follow requests for reshared messages. (We don't need though for forum posts)
375 if ($author['type'] != 'Group') {
376 Logger::log('Send follow request for ' . $item['uri'] . ' (' . $stored . ') to ' . $item['author-link'], Logger::DEBUG);
377 ActivityPub\Transmitter::sendFollowObject($item['uri'], $item['author-link']);
383 * Fetches missing posts
387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
389 private static function fetchMissingActivity($url, $child)
391 if (Config::get('system', 'ostatus_full_threads')) {
395 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
397 $object = ActivityPub::fetchContent($url, $uid);
398 if (empty($object)) {
399 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
403 if (empty($object['id'])) {
404 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
409 $activity['@context'] = $object['@context'];
410 unset($object['@context']);
411 $activity['id'] = $object['id'];
412 $activity['to'] = defaults($object, 'to', []);
413 $activity['cc'] = defaults($object, 'cc', []);
414 $activity['actor'] = $child['author'];
415 $activity['object'] = $object;
416 $activity['published'] = defaults($object, 'published', $child['published']);
417 $activity['type'] = 'Create';
419 $ldactivity = JsonLD::compact($activity);
421 $ldactivity['thread-completion'] = true;
423 ActivityPub\Receiver::processActivity($ldactivity);
424 Logger::log('Activity ' . $url . ' had been fetched and processed.');
428 * perform a "follow" request
430 * @param array $activity
431 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
432 * @throws \ImagickException
434 public static function followUser($activity)
436 $uid = User::getIdForURL($activity['object_id']);
441 $owner = User::getOwnerDataById($uid);
443 $cid = Contact::getIdForURL($activity['actor'], $uid);
445 self::switchContact($cid);
446 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
447 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
452 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
453 'author-link' => $activity['actor']];
455 // Ensure that the contact has got the right network type
456 self::switchContact($item['author-id']);
458 Contact::addRelationship($owner, $contact, $item);
459 $cid = Contact::getIdForURL($activity['actor'], $uid);
464 if (empty($contact)) {
465 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
468 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
472 * Update the given profile
474 * @param array $activity
477 public static function updatePerson($activity)
479 if (empty($activity['object_id'])) {
483 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
484 APContact::getByURL($activity['object_id'], true);
488 * Delete the given profile
490 * @param array $activity
491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
493 public static function deletePerson($activity)
495 if (empty($activity['object_id']) || empty($activity['actor'])) {
496 Logger::log('Empty object id or actor.', Logger::DEBUG);
500 if ($activity['object_id'] != $activity['actor']) {
501 Logger::log('Object id does not match actor.', Logger::DEBUG);
505 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
506 while ($contact = DBA::fetch($contacts)) {
507 Contact::remove($contact['id']);
509 DBA::close($contacts);
511 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
515 * Accept a follow request
517 * @param array $activity
518 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
519 * @throws \ImagickException
521 public static function acceptFollowUser($activity)
523 $uid = User::getIdForURL($activity['object_actor']);
528 $cid = Contact::getIdForURL($activity['actor'], $uid);
530 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
534 self::switchContact($cid);
536 $fields = ['pending' => false];
538 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
539 if ($contact['rel'] == Contact::FOLLOWER) {
540 $fields['rel'] = Contact::FRIEND;
543 $condition = ['id' => $cid];
544 DBA::update('contact', $fields, $condition);
545 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
549 * Reject a follow request
551 * @param array $activity
552 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
553 * @throws \ImagickException
555 public static function rejectFollowUser($activity)
557 $uid = User::getIdForURL($activity['object_actor']);
562 $cid = Contact::getIdForURL($activity['actor'], $uid);
564 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
568 self::switchContact($cid);
570 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
571 Contact::remove($cid);
572 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
574 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
579 * Undo activity like "like" or "dislike"
581 * @param array $activity
582 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
583 * @throws \ImagickException
585 public static function undoActivity($activity)
587 if (empty($activity['object_id'])) {
591 if (empty($activity['object_actor'])) {
595 $author_id = Contact::getIdForURL($activity['object_actor']);
596 if (empty($author_id)) {
600 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
604 * Activity to remove a follower
606 * @param array $activity
607 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
608 * @throws \ImagickException
610 public static function undoFollowUser($activity)
612 $uid = User::getIdForURL($activity['object_object']);
617 $owner = User::getOwnerDataById($uid);
619 $cid = Contact::getIdForURL($activity['actor'], $uid);
621 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
625 self::switchContact($cid);
627 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
628 if (!DBA::isResult($contact)) {
632 Contact::removeFollower($owner, $contact);
633 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
637 * Switches a contact to AP if needed
639 * @param integer $cid Contact ID
642 private static function switchContact($cid)
644 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
645 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
649 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
650 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
654 * Collects implicit mentions like:
655 * - the author of the parent item
656 * - all the mentioned conversants in the parent item
658 * @param array $parent Item array with at least ['id', 'author-link', 'alias']
660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662 private static function getImplicitMentionList(array $parent)
664 if (Config::get('system', 'disable_implicit_mentions')) {
668 $parent_terms = Term::tagArrayFromItemId($parent['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
670 $parent_author = Contact::getDetailsByURL($parent['author-link'], 0);
672 $implicit_mentions = [
673 $parent_author['url'],
674 $parent_author['nurl'],
675 $parent_author['alias'],
678 if ($parent['alias']) {
679 $implicit_mentions[] = $parent['alias'];
682 foreach ($parent_terms as $term) {
683 $contact = Contact::getDetailsByURL($term['url'], 0);
684 if (!empty($contact)) {
685 $implicit_mentions[] = $contact['url'];
686 $implicit_mentions[] = $contact['nurl'];
687 $implicit_mentions[] = $contact['alias'];
691 return $implicit_mentions;
695 * Strips from the body prepended implicit mentions
697 * @param string $body
698 * @param array $potential_mentions
701 private static function removeImplicitMentionsFromBody($body, array $potential_mentions)
703 if (Config::get('system', 'disable_implicit_mentions')) {
709 // Extract one prepended mention at a time from the body
710 while(preg_match('#^(@\[url=([^\]]+)].*?\[\/url]\s)(.*)#mis', $body, $matches)) {
711 if (!in_array($matches[2], $potential_mentions) ) {
712 $kept_mentions[] = $matches[1];
718 // Re-appending the kept mentions to the body after extraction
719 $kept_mentions[] = $body;
721 return implode('', $kept_mentions);
724 private static function convertImplicitMentionsInTags($activity_tags, array $potential_mentions)
726 if (Config::get('system', 'disable_implicit_mentions')) {
727 return $activity_tags;
730 foreach ($activity_tags as $index => $tag) {
731 if (in_array($tag['href'], $potential_mentions)) {
732 $activity_tags[$index]['name'] = preg_replace(
733 '/' . preg_quote(Term::TAG_CHARACTER[Term::MENTION], '/') . '/',
734 Term::TAG_CHARACTER[Term::IMPLICIT_MENTION],
735 $activity_tags[$index]['name'],
741 return $activity_tags;
744 public static function testImplicitMentions($item, $source)
746 $parent = Item::selectFirst(['id', 'guid', 'author-link', 'alias'], ['uri' => $item['thr-parent']]);
748 $implicit_mentions = self::getImplicitMentionList($parent);
749 var_dump($implicit_mentions);
751 $object = json_decode($source, true)['object'];
754 $content = HTML::toBBCode($object['content']);
755 $content = self::convertMentions($content);
758 'tags' => $object['tag'],
759 'content' => $content
764 $activity['content'] = Processor::removeImplicitMentionsFromBody($activity['content'], $implicit_mentions);
765 $activity['tags'] = Processor::convertImplicitMentionsInTags($activity['tags'], $implicit_mentions);