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'];
268 if (($item['parent-uri'] != $item['uri']) && ($item['gravity'] == GRAVITY_COMMENT)) {
269 $item_private = !in_array(0, $activity['item_receiver']);
270 $parent = Item::selectFirst(['private'], ['uri' => $item['parent-uri']]);
271 if (!DBA::isResult($parent)) {
274 if ($item_private && !$parent['private']) {
275 Logger::log('Item ' . $item['uri'] . ' is private but the parent ' . $item['parent-uri'] . ' is not. So we drop it.');
280 $item['created'] = $activity['published'];
281 $item['edited'] = $activity['updated'];
282 $item['guid'] = $activity['diaspora:guid'];
283 $item['title'] = HTML::toBBCode($activity['name']);
284 $item['content-warning'] = HTML::toBBCode($activity['summary']);
285 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
286 $item['body'] = self::convertMentions($content);
288 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
289 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
292 $item['location'] = $activity['location'];
294 if (!empty($item['latitude']) && !empty($item['longitude'])) {
295 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
298 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
299 $item['app'] = $activity['generator'];
300 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
302 $item = self::constructAttachList($activity['attachments'], $item);
304 if (!empty($activity['source'])) {
305 $item['body'] = $activity['source'];
308 foreach ($activity['receiver'] as $receiver) {
309 $item['uid'] = $receiver;
310 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
312 if (($receiver != 0) && empty($item['contact-id'])) {
313 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
316 if ($activity['object_type'] == 'as:Event') {
317 self::createEvent($activity, $item);
320 $item_id = Item::insert($item);
321 Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
326 * Fetches missing posts
331 private static function fetchMissingActivity($url, $child)
333 if (Config::get('system', 'ostatus_full_threads')) {
337 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
339 $object = ActivityPub::fetchContent($url, $uid);
340 if (empty($object)) {
341 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
345 if (empty($object['id'])) {
346 Logger::log('Activity ' . $url . ' has got not id, aborting. ' . json_encode($object));
351 $activity['@context'] = $object['@context'];
352 unset($object['@context']);
353 $activity['id'] = $object['id'];
354 $activity['to'] = defaults($object, 'to', []);
355 $activity['cc'] = defaults($object, 'cc', []);
356 $activity['actor'] = $child['author'];
357 $activity['object'] = $object;
358 $activity['published'] = defaults($object, 'published', $child['published']);
359 $activity['type'] = 'Create';
361 $ldactivity = JsonLD::compact($activity);
363 $ldactivity['thread-completion'] = true;
365 ActivityPub\Receiver::processActivity($ldactivity);
366 Logger::log('Activity ' . $url . ' had been fetched and processed.');
370 * perform a "follow" request
372 * @param array $activity
374 public static function followUser($activity)
376 $uid = User::getIdForURL($activity['object_id']);
381 $owner = User::getOwnerDataById($uid);
383 $cid = Contact::getIdForURL($activity['actor'], $uid);
385 self::switchContact($cid);
386 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
387 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
392 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
393 'author-link' => $activity['actor']];
395 // Ensure that the contact has got the right network type
396 self::switchContact($item['author-id']);
398 Contact::addRelationship($owner, $contact, $item);
399 $cid = Contact::getIdForURL($activity['actor'], $uid);
404 if (empty($contact)) {
405 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
408 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
412 * Update the given profile
414 * @param array $activity
416 public static function updatePerson($activity)
418 if (empty($activity['object_id'])) {
422 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
423 APContact::getByURL($activity['object_id'], true);
427 * Delete the given profile
429 * @param array $activity
431 public static function deletePerson($activity)
433 if (empty($activity['object_id']) || empty($activity['actor'])) {
434 Logger::log('Empty object id or actor.', Logger::DEBUG);
438 if ($activity['object_id'] != $activity['actor']) {
439 Logger::log('Object id does not match actor.', Logger::DEBUG);
443 $contacts = DBA::select('contact', ['id'], ['nurl' => Strings::normaliseLink($activity['object_id'])]);
444 while ($contact = DBA::fetch($contacts)) {
445 Contact::remove($contact['id']);
447 DBA::close($contacts);
449 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
453 * Accept a follow request
455 * @param array $activity
457 public static function acceptFollowUser($activity)
459 $uid = User::getIdForURL($activity['object_actor']);
464 $owner = User::getOwnerDataById($uid);
466 $cid = Contact::getIdForURL($activity['actor'], $uid);
468 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
472 self::switchContact($cid);
474 $fields = ['pending' => false];
476 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
477 if ($contact['rel'] == Contact::FOLLOWER) {
478 $fields['rel'] = Contact::FRIEND;
481 $condition = ['id' => $cid];
482 DBA::update('contact', $fields, $condition);
483 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
487 * Reject a follow request
489 * @param array $activity
491 public static function rejectFollowUser($activity)
493 $uid = User::getIdForURL($activity['object_actor']);
498 $owner = User::getOwnerDataById($uid);
500 $cid = Contact::getIdForURL($activity['actor'], $uid);
502 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
506 self::switchContact($cid);
508 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
509 Contact::remove($cid);
510 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
512 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
517 * Undo activity like "like" or "dislike"
519 * @param array $activity
521 public static function undoActivity($activity)
523 if (empty($activity['object_id'])) {
527 if (empty($activity['object_actor'])) {
531 $author_id = Contact::getIdForURL($activity['object_actor']);
532 if (empty($author_id)) {
536 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
540 * Activity to remove a follower
542 * @param array $activity
544 public static function undoFollowUser($activity)
546 $uid = User::getIdForURL($activity['object_object']);
551 $owner = User::getOwnerDataById($uid);
553 $cid = Contact::getIdForURL($activity['actor'], $uid);
555 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
559 self::switchContact($cid);
561 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
562 if (!DBA::isResult($contact)) {
566 Contact::removeFollower($owner, $contact);
567 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
571 * Switches a contact to AP if needed
573 * @param integer $cid Contact ID
575 private static function switchContact($cid)
577 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
578 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
582 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
583 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);