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 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
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
148 public static function createItem($activity)
151 $item['verb'] = ACTIVITY_POST;
152 $item['parent-uri'] = $activity['reply-to-id'];
154 if ($activity['reply-to-id'] == $activity['id']) {
155 $item['gravity'] = GRAVITY_PARENT;
156 $item['object-type'] = ACTIVITY_OBJ_NOTE;
158 $item['gravity'] = GRAVITY_COMMENT;
159 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
162 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
163 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
164 self::fetchMissingActivity($activity['reply-to-id'], $activity);
167 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
169 self::postItem($activity, $item);
175 * @param array $activity
177 public static function deleteItem($activity)
179 $owner = Contact::getIdForURL($activity['actor']);
181 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
182 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
186 * Prepare the item array for an activity
188 * @param array $activity Activity array
189 * @param string $verb Activity verb
191 public static function createActivity($activity, $verb)
194 $item['verb'] = $verb;
195 $item['parent-uri'] = $activity['object_id'];
196 $item['gravity'] = GRAVITY_ACTIVITY;
197 $item['object-type'] = ACTIVITY_OBJ_NOTE;
199 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
201 self::postItem($activity, $item);
207 * @param array $activity Activity array
210 public static function createEvent($activity, $item)
212 $event['summary'] = HTML::toBBCode($activity['name']);
213 $event['desc'] = HTML::toBBCode($activity['content']);
214 $event['start'] = $activity['start-time'];
215 $event['finish'] = $activity['end-time'];
216 $event['nofinish'] = empty($event['finish']);
217 $event['location'] = $activity['location'];
218 $event['adjust'] = true;
219 $event['cid'] = $item['contact-id'];
220 $event['uid'] = $item['uid'];
221 $event['uri'] = $item['uri'];
222 $event['edited'] = $item['edited'];
223 $event['private'] = $item['private'];
224 $event['guid'] = $item['guid'];
225 $event['plink'] = $item['plink'];
227 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
228 $ev = DBA::selectFirst('event', ['id'], $condition);
229 if (DBA::isResult($ev)) {
230 $event['id'] = $ev['id'];
233 $event_id = Event::store($event);
234 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
238 * Creates an item post
240 * @param array $activity Activity data
241 * @param array $item item array
243 private static function postItem($activity, $item)
245 /// @todo What to do with $activity['context']?
247 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
248 Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
252 $item['network'] = Protocol::ACTIVITYPUB;
253 $item['private'] = !in_array(0, $activity['receiver']);
254 $item['author-link'] = $activity['author'];
255 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
257 if (empty($activity['thread-completion'])) {
258 $item['owner-link'] = $activity['actor'];
259 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
261 Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
262 $item['owner-link'] = $item['author-link'];
263 $item['owner-id'] = $item['author-id'];
266 $item['uri'] = $activity['id'];
267 $item['created'] = $activity['published'];
268 $item['edited'] = $activity['updated'];
269 $item['guid'] = $activity['diaspora:guid'];
270 $item['title'] = HTML::toBBCode($activity['name']);
271 $item['content-warning'] = HTML::toBBCode($activity['summary']);
272 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
273 $item['body'] = self::convertMentions($content);
275 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
276 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
279 $item['location'] = $activity['location'];
281 if (!empty($item['latitude']) && !empty($item['longitude'])) {
282 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
285 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
286 $item['app'] = $activity['generator'];
287 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
289 $item = self::constructAttachList($activity['attachments'], $item);
291 if (!empty($activity['source'])) {
292 $item['body'] = $activity['source'];
295 foreach ($activity['receiver'] as $receiver) {
296 $item['uid'] = $receiver;
297 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
299 if (($receiver != 0) && empty($item['contact-id'])) {
300 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
303 if ($activity['object_type'] == 'as:Event') {
304 self::createEvent($activity, $item);
307 $item_id = Item::insert($item);
308 Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
313 * Fetches missing posts
318 private static function fetchMissingActivity($url, $child)
320 if (Config::get('system', 'ostatus_full_threads')) {
324 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
326 $object = ActivityPub::fetchContent($url, $uid);
327 if (empty($object)) {
328 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
332 if (empty($object['id'])) {
333 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
338 $activity['@context'] = $object['@context'];
339 unset($object['@context']);
340 $activity['id'] = $object['id'];
341 $activity['to'] = defaults($object, 'to', []);
342 $activity['cc'] = defaults($object, 'cc', []);
343 $activity['actor'] = $child['author'];
344 $activity['object'] = $object;
345 $activity['published'] = defaults($object, 'published', $child['published']);
346 $activity['type'] = 'Create';
348 $ldactivity = JsonLD::compact($activity);
350 $ldactivity['thread-completion'] = true;
352 ActivityPub\Receiver::processActivity($ldactivity);
353 Logger::log('Activity ' . $url . ' had been fetched and processed.');
357 * perform a "follow" request
359 * @param array $activity
361 public static function followUser($activity)
363 $uid = User::getIdForURL($activity['object_id']);
368 $owner = User::getOwnerDataById($uid);
370 $cid = Contact::getIdForURL($activity['actor'], $uid);
372 self::switchContact($cid);
373 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
374 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
379 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
380 'author-link' => $activity['actor']];
382 // Ensure that the contact has got the right network type
383 self::switchContact($item['author-id']);
385 Contact::addRelationship($owner, $contact, $item);
386 $cid = Contact::getIdForURL($activity['actor'], $uid);
391 if (empty($contact)) {
392 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
395 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
399 * Update the given profile
401 * @param array $activity
403 public static function updatePerson($activity)
405 if (empty($activity['object_id'])) {
409 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
410 APContact::getByURL($activity['object_id'], true);
414 * Delete the given profile
416 * @param array $activity
418 public static function deletePerson($activity)
420 if (empty($activity['object_id']) || empty($activity['actor'])) {
421 Logger::log('Empty object id or actor.', Logger::DEBUG);
425 if ($activity['object_id'] != $activity['actor']) {
426 Logger::log('Object id does not match actor.', Logger::DEBUG);
430 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
431 while ($contact = DBA::fetch($contacts)) {
432 Contact::remove($contact['id']);
434 DBA::close($contacts);
436 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
440 * Accept a follow request
442 * @param array $activity
444 public static function acceptFollowUser($activity)
446 $uid = User::getIdForURL($activity['object_actor']);
451 $owner = User::getOwnerDataById($uid);
453 $cid = Contact::getIdForURL($activity['actor'], $uid);
455 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
459 self::switchContact($cid);
461 $fields = ['pending' => false];
463 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
464 if ($contact['rel'] == Contact::FOLLOWER) {
465 $fields['rel'] = Contact::FRIEND;
468 $condition = ['id' => $cid];
469 DBA::update('contact', $fields, $condition);
470 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
474 * Reject a follow request
476 * @param array $activity
478 public static function rejectFollowUser($activity)
480 $uid = User::getIdForURL($activity['object_actor']);
485 $owner = User::getOwnerDataById($uid);
487 $cid = Contact::getIdForURL($activity['actor'], $uid);
489 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
493 self::switchContact($cid);
495 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
496 Contact::remove($cid);
497 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
499 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
504 * Undo activity like "like" or "dislike"
506 * @param array $activity
508 public static function undoActivity($activity)
510 if (empty($activity['object_id'])) {
514 if (empty($activity['object_actor'])) {
518 $author_id = Contact::getIdForURL($activity['object_actor']);
519 if (empty($author_id)) {
523 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
527 * Activity to remove a follower
529 * @param array $activity
531 public static function undoFollowUser($activity)
533 $uid = User::getIdForURL($activity['object_object']);
538 $owner = User::getOwnerDataById($uid);
540 $cid = Contact::getIdForURL($activity['actor'], $uid);
542 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
546 self::switchContact($cid);
548 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
549 if (!DBA::isResult($contact)) {
553 Contact::removeFollower($owner, $contact);
554 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
558 * Switches a contact to AP if needed
560 * @param integer $cid Contact ID
562 private static function switchContact($cid)
564 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
565 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
569 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
570 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);