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\User;
17 use Friendica\Protocol\ActivityPub;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\JsonLD;
20 use Friendica\Util\Strings;
23 * ActivityPub Processor Protocol class
28 * Converts mentions from Pleroma into the Friendica format
32 * @return string converted body
34 private static function convertMentions($body)
36 $URLSearchString = "^\[\]";
37 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
43 * Replaces emojis in the body
45 * @param array $emojis
48 * @return string with replaced emojis
50 public static function replaceEmojis($emojis, $body)
52 foreach ($emojis as $emoji) {
53 $replace = '[class=emoji mastodon][img=' . $emoji['href'] . ']' . $emoji['name'] . '[/img][/class]';
54 $body = str_replace($emoji['name'], $replace, $body);
60 * Constructs a string with tags for a given tag array
63 * @param boolean $sensitive
65 * @return string with tags
67 private static function constructTagList($tags, $sensitive)
74 foreach ($tags as $tag) {
75 if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag'])) {
76 if (!empty($tag_text)) {
80 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
84 /// @todo add nsfw for $sensitive
90 * Add attachment data to the item array
92 * @param array $attachments
97 private static function constructAttachList($attachments, $item)
99 if (empty($attachments)) {
103 foreach ($attachments as $attach) {
104 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
105 if ($filetype == 'image') {
106 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
108 if (!empty($item["attach"])) {
109 $item["attach"] .= ',';
111 $item["attach"] = '';
113 if (!isset($attach['length'])) {
114 $attach['length'] = "0";
116 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
126 * @param array $activity Activity array
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
129 public static function updateItem($activity)
132 $item['changed'] = DateTimeFormat::utcNow();
133 $item['edited'] = $activity['updated'];
134 $item['title'] = HTML::toBBCode($activity['name']);
135 $item['content-warning'] = HTML::toBBCode($activity['summary']);
136 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
137 $item['body'] = self::convertMentions($content);
138 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
140 Item::update($item, ['uri' => $activity['id']]);
144 * Prepares data for a message
146 * @param array $activity Activity array
147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
148 * @throws \ImagickException
150 public static function createItem($activity)
153 $item['verb'] = ACTIVITY_POST;
154 $item['parent-uri'] = $activity['reply-to-id'];
156 if ($activity['reply-to-id'] == $activity['id']) {
157 $item['gravity'] = GRAVITY_PARENT;
158 $item['object-type'] = ACTIVITY_OBJ_NOTE;
160 $item['gravity'] = GRAVITY_COMMENT;
161 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
164 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
165 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
166 self::fetchMissingActivity($activity['reply-to-id'], $activity);
169 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
171 self::postItem($activity, $item);
177 * @param array $activity
178 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
179 * @throws \ImagickException
181 public static function deleteItem($activity)
183 $owner = Contact::getIdForURL($activity['actor']);
185 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
186 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
190 * Prepare the item array for an activity
192 * @param array $activity Activity array
193 * @param string $verb Activity verb
194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
195 * @throws \ImagickException
197 public static function createActivity($activity, $verb)
200 $item['verb'] = $verb;
201 $item['parent-uri'] = $activity['object_id'];
202 $item['gravity'] = GRAVITY_ACTIVITY;
203 $item['object-type'] = ACTIVITY_OBJ_NOTE;
205 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
207 self::postItem($activity, $item);
213 * @param array $activity Activity array
217 public static function createEvent($activity, $item)
219 $event['summary'] = HTML::toBBCode($activity['name']);
220 $event['desc'] = HTML::toBBCode($activity['content']);
221 $event['start'] = $activity['start-time'];
222 $event['finish'] = $activity['end-time'];
223 $event['nofinish'] = empty($event['finish']);
224 $event['location'] = $activity['location'];
225 $event['adjust'] = true;
226 $event['cid'] = $item['contact-id'];
227 $event['uid'] = $item['uid'];
228 $event['uri'] = $item['uri'];
229 $event['edited'] = $item['edited'];
230 $event['private'] = $item['private'];
231 $event['guid'] = $item['guid'];
232 $event['plink'] = $item['plink'];
234 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
235 $ev = DBA::selectFirst('event', ['id'], $condition);
236 if (DBA::isResult($ev)) {
237 $event['id'] = $ev['id'];
240 $event_id = Event::store($event);
241 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
245 * Creates an item post
247 * @param array $activity Activity data
248 * @param array $item item array
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 private static function postItem($activity, $item)
254 /// @todo What to do with $activity['context']?
256 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
257 Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
261 $item['network'] = Protocol::ACTIVITYPUB;
262 $item['private'] = !in_array(0, $activity['receiver']);
263 $item['author-link'] = $activity['author'];
264 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
266 if (empty($activity['thread-completion'])) {
267 $item['owner-link'] = $activity['actor'];
268 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
270 Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
271 $item['owner-link'] = $item['author-link'];
272 $item['owner-id'] = $item['author-id'];
275 $item['uri'] = $activity['id'];
277 if (($item['parent-uri'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
278 $item_private = !in_array(0, $activity['item_receiver']);
279 $parent = Item::selectFirst(['private'], ['uri' => $item['parent-uri']]);
280 if (!DBA::isResult($parent)) {
283 if ($item_private && !$parent['private']) {
284 Logger::log('Item ' . $item['uri'] . ' is private but the parent ' . $item['parent-uri'] . ' is not. So we drop it.');
289 $item['created'] = $activity['published'];
290 $item['edited'] = $activity['updated'];
291 $item['guid'] = $activity['diaspora:guid'];
292 $item['title'] = HTML::toBBCode($activity['name']);
293 $item['content-warning'] = HTML::toBBCode($activity['summary']);
294 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
295 $item['body'] = self::convertMentions($content);
297 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
298 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
301 $item['location'] = $activity['location'];
303 if (!empty($item['latitude']) && !empty($item['longitude'])) {
304 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
307 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
308 $item['app'] = $activity['generator'];
309 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
311 $item = self::constructAttachList($activity['attachments'], $item);
313 if (!empty($activity['source'])) {
314 $item['body'] = $activity['source'];
317 foreach ($activity['receiver'] as $receiver) {
318 $item['uid'] = $receiver;
319 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
321 if (($receiver != 0) && empty($item['contact-id'])) {
322 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
325 if ($activity['object_type'] == 'as:Event') {
326 self::createEvent($activity, $item);
329 $item_id = Item::insert($item);
330 Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
335 * Fetches missing posts
339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
341 private static function fetchMissingActivity($url, $child)
343 if (Config::get('system', 'ostatus_full_threads')) {
347 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
349 $object = ActivityPub::fetchContent($url, $uid);
350 if (empty($object)) {
351 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
355 if (empty($object['id'])) {
356 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
361 $activity['@context'] = $object['@context'];
362 unset($object['@context']);
363 $activity['id'] = $object['id'];
364 $activity['to'] = defaults($object, 'to', []);
365 $activity['cc'] = defaults($object, 'cc', []);
366 $activity['actor'] = $child['author'];
367 $activity['object'] = $object;
368 $activity['published'] = defaults($object, 'published', $child['published']);
369 $activity['type'] = 'Create';
371 $ldactivity = JsonLD::compact($activity);
373 $ldactivity['thread-completion'] = true;
375 ActivityPub\Receiver::processActivity($ldactivity);
376 Logger::log('Activity ' . $url . ' had been fetched and processed.');
380 * perform a "follow" request
382 * @param array $activity
383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
384 * @throws \ImagickException
386 public static function followUser($activity)
388 $uid = User::getIdForURL($activity['object_id']);
393 $owner = User::getOwnerDataById($uid);
395 $cid = Contact::getIdForURL($activity['actor'], $uid);
397 self::switchContact($cid);
398 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
399 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
404 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
405 'author-link' => $activity['actor']];
407 // Ensure that the contact has got the right network type
408 self::switchContact($item['author-id']);
410 Contact::addRelationship($owner, $contact, $item);
411 $cid = Contact::getIdForURL($activity['actor'], $uid);
416 if (empty($contact)) {
417 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
420 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
424 * Update the given profile
426 * @param array $activity
429 public static function updatePerson($activity)
431 if (empty($activity['object_id'])) {
435 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
436 APContact::getByURL($activity['object_id'], true);
440 * Delete the given profile
442 * @param array $activity
443 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
445 public static function deletePerson($activity)
447 if (empty($activity['object_id']) || empty($activity['actor'])) {
448 Logger::log('Empty object id or actor.', Logger::DEBUG);
452 if ($activity['object_id'] != $activity['actor']) {
453 Logger::log('Object id does not match actor.', Logger::DEBUG);
457 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
458 while ($contact = DBA::fetch($contacts)) {
459 Contact::remove($contact['id']);
461 DBA::close($contacts);
463 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
467 * Accept a follow request
469 * @param array $activity
470 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
471 * @throws \ImagickException
473 public static function acceptFollowUser($activity)
475 $uid = User::getIdForURL($activity['object_actor']);
480 $cid = Contact::getIdForURL($activity['actor'], $uid);
482 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
486 self::switchContact($cid);
488 $fields = ['pending' => false];
490 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
491 if ($contact['rel'] == Contact::FOLLOWER) {
492 $fields['rel'] = Contact::FRIEND;
495 $condition = ['id' => $cid];
496 DBA::update('contact', $fields, $condition);
497 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
501 * Reject a follow request
503 * @param array $activity
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
505 * @throws \ImagickException
507 public static function rejectFollowUser($activity)
509 $uid = User::getIdForURL($activity['object_actor']);
514 $cid = Contact::getIdForURL($activity['actor'], $uid);
516 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
520 self::switchContact($cid);
522 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
523 Contact::remove($cid);
524 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
526 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
531 * Undo activity like "like" or "dislike"
533 * @param array $activity
534 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
535 * @throws \ImagickException
537 public static function undoActivity($activity)
539 if (empty($activity['object_id'])) {
543 if (empty($activity['object_actor'])) {
547 $author_id = Contact::getIdForURL($activity['object_actor']);
548 if (empty($author_id)) {
552 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
556 * Activity to remove a follower
558 * @param array $activity
559 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
560 * @throws \ImagickException
562 public static function undoFollowUser($activity)
564 $uid = User::getIdForURL($activity['object_object']);
569 $owner = User::getOwnerDataById($uid);
571 $cid = Contact::getIdForURL($activity['actor'], $uid);
573 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
577 self::switchContact($cid);
579 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
580 if (!DBA::isResult($contact)) {
584 Contact::removeFollower($owner, $contact);
585 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
589 * Switches a contact to AP if needed
591 * @param integer $cid Contact ID
594 private static function switchContact($cid)
596 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
597 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
601 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
602 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);