3 * @file src/Protocol/ActivityPub/Processor.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Core\Logger;
9 use Friendica\Core\Protocol;
10 use Friendica\Model\Conversation;
11 use Friendica\Model\Contact;
12 use Friendica\Model\APContact;
13 use Friendica\Model\Item;
14 use Friendica\Model\Event;
15 use Friendica\Model\User;
16 use Friendica\Content\Text\HTML;
17 use Friendica\Util\JsonLD;
18 use Friendica\Core\Config;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Util\DateTimeFormat;
23 * ActivityPub Processor Protocol class
28 * Converts mentions from Pleroma into the Friendica format
32 * @return 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
128 public static function updateItem($activity)
131 $item['changed'] = DateTimeFormat::utcNow();
132 $item['edited'] = $activity['updated'];
133 $item['title'] = HTML::toBBCode($activity['name']);
134 $item['content-warning'] = HTML::toBBCode($activity['summary']);
135 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
136 $item['body'] = self::convertMentions($content);
137 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
139 Item::update($item, ['uri' => $activity['id']]);
143 * Prepares data for a message
145 * @param array $activity Activity array
147 public static function createItem($activity)
150 $item['verb'] = ACTIVITY_POST;
151 $item['parent-uri'] = $activity['reply-to-id'];
153 if ($activity['reply-to-id'] == $activity['id']) {
154 $item['gravity'] = GRAVITY_PARENT;
155 $item['object-type'] = ACTIVITY_OBJ_NOTE;
157 $item['gravity'] = GRAVITY_COMMENT;
158 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
161 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
162 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
163 self::fetchMissingActivity($activity['reply-to-id'], $activity);
166 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
168 self::postItem($activity, $item);
174 * @param array $activity
176 public static function deleteItem($activity)
178 $owner = Contact::getIdForURL($activity['actor']);
180 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, Logger::DEBUG);
181 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
185 * Prepare the item array for an activity
187 * @param array $activity Activity array
188 * @param string $verb Activity verb
190 public static function createActivity($activity, $verb)
193 $item['verb'] = $verb;
194 $item['parent-uri'] = $activity['object_id'];
195 $item['gravity'] = GRAVITY_ACTIVITY;
196 $item['object-type'] = ACTIVITY_OBJ_NOTE;
198 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
200 self::postItem($activity, $item);
206 * @param array $activity Activity array
209 public static function createEvent($activity, $item)
211 $event['summary'] = $activity['name'];
212 $event['desc'] = $activity['content'];
213 $event['start'] = $activity['start-time'];
214 $event['finish'] = $activity['end-time'];
215 $event['nofinish'] = empty($event['finish']);
216 $event['location'] = $activity['location'];
217 $event['adjust'] = true;
218 $event['cid'] = $item['contact-id'];
219 $event['uid'] = $item['uid'];
220 $event['uri'] = $item['uri'];
221 $event['edited'] = $item['edited'];
222 $event['private'] = $item['private'];
223 $event['guid'] = $item['guid'];
224 $event['plink'] = $item['plink'];
226 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
227 $ev = DBA::selectFirst('event', ['id'], $condition);
228 if (DBA::isResult($ev)) {
229 $event['id'] = $ev['id'];
232 $event_id = Event::store($event);
233 Logger::log('Event '.$event_id.' was stored', Logger::DEBUG);
237 * Creates an item post
239 * @param array $activity Activity data
240 * @param array $item item array
242 private static function postItem($activity, $item)
244 /// @todo What to do with $activity['context']?
246 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
247 Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', Logger::DEBUG);
251 $item['network'] = Protocol::ACTIVITYPUB;
252 $item['private'] = !in_array(0, $activity['receiver']);
253 $item['author-link'] = $activity['author'];
254 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
256 if (empty($activity['thread-completion'])) {
257 $item['owner-link'] = $activity['actor'];
258 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
260 Logger::log('Ignoring actor because of thread completion.', Logger::DEBUG);
261 $item['owner-link'] = $item['author-link'];
262 $item['owner-id'] = $item['author-id'];
265 $item['uri'] = $activity['id'];
266 $item['created'] = $activity['published'];
267 $item['edited'] = $activity['updated'];
268 $item['guid'] = $activity['diaspora:guid'];
269 $item['title'] = HTML::toBBCode($activity['name']);
270 $item['content-warning'] = HTML::toBBCode($activity['summary']);
271 $content = self::replaceEmojis($activity['emojis'], HTML::toBBCode($activity['content']));
272 $item['body'] = self::convertMentions($content);
274 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
275 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
278 $item['location'] = $activity['location'];
280 if (!empty($item['latitude']) && !empty($item['longitude'])) {
281 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
284 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
285 $item['app'] = $activity['generator'];
286 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
288 $item = self::constructAttachList($activity['attachments'], $item);
290 if (!empty($activity['source'])) {
291 $item['body'] = $activity['source'];
294 foreach ($activity['receiver'] as $receiver) {
295 $item['uid'] = $receiver;
296 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
298 if (($receiver != 0) && empty($item['contact-id'])) {
299 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
302 if ($activity['object_type'] == 'as:Event') {
303 self::createEvent($activity, $item);
306 $item_id = Item::insert($item);
307 Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
312 * Fetches missing posts
317 private static function fetchMissingActivity($url, $child)
319 if (Config::get('system', 'ostatus_full_threads')) {
323 $uid = ActivityPub\Receiver::getFirstUserFromReceivers($child['receiver']);
325 $object = ActivityPub::fetchContent($url, $uid);
326 if (empty($object)) {
327 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
332 $activity['@context'] = $object['@context'];
333 unset($object['@context']);
334 $activity['id'] = $object['id'];
335 $activity['to'] = defaults($object, 'to', []);
336 $activity['cc'] = defaults($object, 'cc', []);
337 $activity['actor'] = $child['author'];
338 $activity['object'] = $object;
339 $activity['published'] = defaults($object, 'published', $child['published']);
340 $activity['type'] = 'Create';
342 $ldactivity = JsonLD::compact($activity);
344 $ldactivity['thread-completion'] = true;
346 ActivityPub\Receiver::processActivity($ldactivity);
347 Logger::log('Activity ' . $url . ' had been fetched and processed.');
351 * perform a "follow" request
353 * @param array $activity
355 public static function followUser($activity)
357 $uid = User::getIdForURL($activity['object_id']);
362 $owner = User::getOwnerDataById($uid);
364 $cid = Contact::getIdForURL($activity['actor'], $uid);
366 self::switchContact($cid);
367 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
372 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
373 'author-link' => $activity['actor']];
375 // Ensure that the contact has got the right network type
376 self::switchContact($item['author-id']);
378 Contact::addRelationship($owner, $contact, $item);
379 $cid = Contact::getIdForURL($activity['actor'], $uid);
384 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
385 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
389 * Update the given profile
391 * @param array $activity
393 public static function updatePerson($activity)
395 if (empty($activity['object_id'])) {
399 Logger::log('Updating profile for ' . $activity['object_id'], Logger::DEBUG);
400 APContact::getByURL($activity['object_id'], true);
404 * Delete the given profile
406 * @param array $activity
408 public static function deletePerson($activity)
410 if (empty($activity['object_id']) || empty($activity['actor'])) {
411 Logger::log('Empty object id or actor.', Logger::DEBUG);
415 if ($activity['object_id'] != $activity['actor']) {
416 Logger::log('Object id does not match actor.', Logger::DEBUG);
420 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object_id'])]);
421 while ($contact = DBA::fetch($contacts)) {
422 Contact::remove($contact['id']);
424 DBA::close($contacts);
426 Logger::log('Deleted contact ' . $activity['object_id'], Logger::DEBUG);
430 * Accept a follow request
432 * @param array $activity
434 public static function acceptFollowUser($activity)
436 $uid = User::getIdForURL($activity['object_actor']);
441 $owner = User::getOwnerDataById($uid);
443 $cid = Contact::getIdForURL($activity['actor'], $uid);
445 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
449 self::switchContact($cid);
451 $fields = ['pending' => false];
453 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
454 if ($contact['rel'] == Contact::FOLLOWER) {
455 $fields['rel'] = Contact::FRIEND;
458 $condition = ['id' => $cid];
459 DBA::update('contact', $fields, $condition);
460 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
464 * Reject a follow request
466 * @param array $activity
468 public static function rejectFollowUser($activity)
470 $uid = User::getIdForURL($activity['object_actor']);
475 $owner = User::getOwnerDataById($uid);
477 $cid = Contact::getIdForURL($activity['actor'], $uid);
479 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
483 self::switchContact($cid);
485 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
486 Contact::remove($cid);
487 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', Logger::DEBUG);
489 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', Logger::DEBUG);
494 * Undo activity like "like" or "dislike"
496 * @param array $activity
498 public static function undoActivity($activity)
500 if (empty($activity['object_id'])) {
504 if (empty($activity['object_actor'])) {
508 $author_id = Contact::getIdForURL($activity['object_actor']);
509 if (empty($author_id)) {
513 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
517 * Activity to remove a follower
519 * @param array $activity
521 public static function undoFollowUser($activity)
523 $uid = User::getIdForURL($activity['object_object']);
528 $owner = User::getOwnerDataById($uid);
530 $cid = Contact::getIdForURL($activity['actor'], $uid);
532 Logger::log('No contact found for ' . $activity['actor'], Logger::DEBUG);
536 self::switchContact($cid);
538 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
539 if (!DBA::isResult($contact)) {
543 Contact::removeFollower($owner, $contact);
544 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, Logger::DEBUG);
548 * Switches a contact to AP if needed
550 * @param integer $cid Contact ID
552 private static function switchContact($cid)
554 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
555 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
559 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
560 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);