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\Conversation;
13 use Friendica\Model\Contact;
14 use Friendica\Model\APContact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Event;
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($emojis, $body)
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
66 * @return string with tags
68 private static function constructTagList($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)
133 $item['changed'] = DateTimeFormat::utcNow();
134 $item['edited'] = $activity['updated'];
135 $item['title'] = HTML::toBBCode($activity['name']);
136 $item['content-warning'] = HTML::toBBCode($activity['summary']);
137 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
138 $item['body'] = self::convertMentions($content);
139 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
141 Item::update($item, ['uri' => $activity['id']]);
145 * Prepares data for a message
147 * @param array $activity Activity array
148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
149 * @throws \ImagickException
151 public static function createItem($activity)
154 $item['verb'] = ACTIVITY_POST;
155 $item['parent-uri'] = $activity['reply-to-id'];
157 if ($activity['reply-to-id'] == $activity['id']) {
158 $item['gravity'] = GRAVITY_PARENT;
159 $item['object-type'] = ACTIVITY_OBJ_NOTE;
161 $item['gravity'] = GRAVITY_COMMENT;
162 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
165 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
166 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
167 self::fetchMissingActivity($activity['reply-to-id'], $activity);
170 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
172 self::postItem($activity, $item);
178 * @param array $activity
179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
180 * @throws \ImagickException
182 public static function deleteItem($activity)
184 $owner = Contact::getIdForURL($activity['actor']);
186 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
187 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
191 * Prepare the item array for an activity
193 * @param array $activity Activity array
194 * @param string $verb Activity verb
195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196 * @throws \ImagickException
198 public static function createActivity($activity, $verb)
201 $item['verb'] = $verb;
202 $item['parent-uri'] = $activity['object_id'];
203 $item['gravity'] = GRAVITY_ACTIVITY;
204 $item['object-type'] = ACTIVITY_OBJ_NOTE;
206 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
208 self::postItem($activity, $item);
214 * @param array $activity Activity array
218 public static function createEvent($activity, $item)
220 $event['summary'] = HTML::toBBCode($activity['name']);
221 $event['desc'] = HTML::toBBCode($activity['content']);
222 $event['start'] = $activity['start-time'];
223 $event['finish'] = $activity['end-time'];
224 $event['nofinish'] = empty($event['finish']);
225 $event['location'] = $activity['location'];
226 $event['adjust'] = true;
227 $event['cid'] = $item['contact-id'];
228 $event['uid'] = $item['uid'];
229 $event['uri'] = $item['uri'];
230 $event['edited'] = $item['edited'];
231 $event['private'] = $item['private'];
232 $event['guid'] = $item['guid'];
233 $event['plink'] = $item['plink'];
235 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
236 $ev = DBA::selectFirst('event', ['id'], $condition);
237 if (DBA::isResult($ev)) {
238 $event['id'] = $ev['id'];
241 $event_id = Event::store($event);
242 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
246 * Creates an item post
248 * @param array $activity Activity data
249 * @param array $item item array
250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
251 * @throws \ImagickException
253 private static function postItem($activity, $item)
255 /// @todo What to do with $activity['context']?
257 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
258 Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
262 $item['network'] = Protocol::ACTIVITYPUB;
263 $item['private'] = !in_array(0, $activity['receiver']);
264 $item['author-link'] = $activity['author'];
265 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
267 if (empty($activity['thread-completion'])) {
268 $item['owner-link'] = $activity['actor'];
269 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
271 Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
272 $item['owner-link'] = $item['author-link'];
273 $item['owner-id'] = $item['author-id'];
276 $item['uri'] = $activity['id'];
278 if (($item['parent-uri'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
279 $item_private = !in_array(0, $activity['item_receiver']);
280 $parent = Item::selectFirst(['private'], ['uri' => $item['parent-uri']]);
281 if (!DBA::isResult($parent)) {
284 if ($item_private && !$parent['private']) {
285 Logger::log('Item ' . $item['uri'] . ' is private but the parent ' . $item['parent-uri'] . ' is not. So we drop it.');
290 $item['created'] = $activity['published'];
291 $item['edited'] = $activity['updated'];
292 $item['guid'] = $activity['diaspora:guid'];
293 $item['title'] = HTML::toBBCode($activity['name']);
294 $item['content-warning'] = HTML::toBBCode($activity['summary']);
295 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
296 $item['body'] = self::convertMentions($content);
298 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
299 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
302 $item['location'] = $activity['location'];
304 if (!empty($item['latitude']) && !empty($item['longitude'])) {
305 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
308 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
309 $item['app'] = $activity['generator'];
310 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
312 $item = self::constructAttachList($activity['attachments'], $item);
314 if (!empty($activity['source'])) {
315 $item['body'] = $activity['source'];
318 foreach ($activity['receiver'] as $receiver) {
319 $item['uid'] = $receiver;
320 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
322 if (($receiver != 0) && empty($item['contact-id'])) {
323 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
326 if ($activity['object_type'] == 'as:Event') {
327 self::createEvent($activity, $item);
330 $item_id = Item::insert($item);
331 Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
336 * Fetches missing posts
340 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
342 private static function fetchMissingActivity($url, $child)
344 if (Config::get('system', 'ostatus_full_threads')) {
348 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
350 $object = ActivityPub::fetchContent($url, $uid);
351 if (empty($object)) {
352 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
356 if (empty($object['id'])) {
357 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
362 $activity['@context'] = $object['@context'];
363 unset($object['@context']);
364 $activity['id'] = $object['id'];
365 $activity['to'] = defaults($object, 'to', []);
366 $activity['cc'] = defaults($object, 'cc', []);
367 $activity['actor'] = $child['author'];
368 $activity['object'] = $object;
369 $activity['published'] = defaults($object, 'published', $child['published']);
370 $activity['type'] = 'Create';
372 $ldactivity = JsonLD::compact($activity);
374 $ldactivity['thread-completion'] = true;
376 ActivityPub\Receiver::processActivity($ldactivity);
377 Logger::log('Activity ' . $url . ' had been fetched and processed.');
381 * perform a "follow" request
383 * @param array $activity
384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
385 * @throws \ImagickException
387 public static function followUser($activity)
389 $uid = User::getIdForURL($activity['object_id']);
394 $owner = User::getOwnerDataById($uid);
396 $cid = Contact::getIdForURL($activity['actor'], $uid);
398 self::switchContact($cid);
399 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
400 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
405 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
406 'author-link' => $activity['actor']];
408 // Ensure that the contact has got the right network type
409 self::switchContact($item['author-id']);
411 Contact::addRelationship($owner, $contact, $item);
412 $cid = Contact::getIdForURL($activity['actor'], $uid);
417 if (empty($contact)) {
418 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
421 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
425 * Update the given profile
427 * @param array $activity
430 public static function updatePerson($activity)
432 if (empty($activity['object_id'])) {
436 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
437 APContact::getByURL($activity['object_id'], true);
441 * Delete the given profile
443 * @param array $activity
444 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
446 public static function deletePerson($activity)
448 if (empty($activity['object_id']) || empty($activity['actor'])) {
449 Logger::log('Empty object id or actor.', Logger::DEBUG);
453 if ($activity['object_id'] != $activity['actor']) {
454 Logger::log('Object id does not match actor.', Logger::DEBUG);
458 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
459 while ($contact = DBA::fetch($contacts)) {
460 Contact::remove($contact['id']);
462 DBA::close($contacts);
464 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
468 * Accept a follow request
470 * @param array $activity
471 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472 * @throws \ImagickException
474 public static function acceptFollowUser($activity)
476 $uid = User::getIdForURL($activity['object_actor']);
481 $owner = User::getOwnerDataById($uid);
483 $cid = Contact::getIdForURL($activity['actor'], $uid);
485 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
489 self::switchContact($cid);
491 $fields = ['pending' => false];
493 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
494 if ($contact['rel'] == Contact::FOLLOWER) {
495 $fields['rel'] = Contact::FRIEND;
498 $condition = ['id' => $cid];
499 DBA::update('contact', $fields, $condition);
500 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
504 * Reject a follow request
506 * @param array $activity
507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
508 * @throws \ImagickException
510 public static function rejectFollowUser($activity)
512 $uid = User::getIdForURL($activity['object_actor']);
517 $owner = User::getOwnerDataById($uid);
519 $cid = Contact::getIdForURL($activity['actor'], $uid);
521 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
525 self::switchContact($cid);
527 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
528 Contact::remove($cid);
529 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
531 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
536 * Undo activity like "like" or "dislike"
538 * @param array $activity
539 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
540 * @throws \ImagickException
542 public static function undoActivity($activity)
544 if (empty($activity['object_id'])) {
548 if (empty($activity['object_actor'])) {
552 $author_id = Contact::getIdForURL($activity['object_actor']);
553 if (empty($author_id)) {
557 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
561 * Activity to remove a follower
563 * @param array $activity
564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
565 * @throws \ImagickException
567 public static function undoFollowUser($activity)
569 $uid = User::getIdForURL($activity['object_object']);
574 $owner = User::getOwnerDataById($uid);
576 $cid = Contact::getIdForURL($activity['actor'], $uid);
578 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
582 self::switchContact($cid);
584 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
585 if (!DBA::isResult($contact)) {
589 Contact::removeFollower($owner, $contact);
590 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
594 * Switches a contact to AP if needed
596 * @param integer $cid Contact ID
599 private static function switchContact($cid)
601 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
602 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
606 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
607 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);