3 * @file src/Protocol/ActivityPub/Processor.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Core\Protocol;
9 use Friendica\Model\Conversation;
10 use Friendica\Model\Contact;
11 use Friendica\Model\APContact;
12 use Friendica\Model\Item;
13 use Friendica\Model\User;
14 use Friendica\Content\Text\HTML;
15 use Friendica\Util\JsonLD;
16 use Friendica\Core\Config;
17 use Friendica\Protocol\ActivityPub;
20 * ActivityPub Protocol class
23 * - Store Diaspora signature
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 * Constructs a string with tags for a given tag array
46 * @param boolean $sensitive
48 * @return string with tags
50 private static function constructTagList($tags, $sensitive)
57 foreach ($tags as $tag) {
58 if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag'])) {
59 if (!empty($tag_text)) {
63 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
67 /// @todo add nsfw for $sensitive
73 * Add attachment data to the item array
75 * @param array $attachments
80 private static function constructAttachList($attachments, $item)
82 if (empty($attachments)) {
86 foreach ($attachments as $attach) {
87 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
88 if ($filetype == 'image') {
89 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
91 if (!empty($item["attach"])) {
92 $item["attach"] .= ',';
96 if (!isset($attach['length'])) {
97 $attach['length'] = "0";
99 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
107 * Prepares data for a message
109 * @param array $activity Activity array
111 public static function createItem($activity)
114 $item['verb'] = ACTIVITY_POST;
115 $item['parent-uri'] = $activity['reply-to-id'];
117 if ($activity['reply-to-id'] == $activity['id']) {
118 $item['gravity'] = GRAVITY_PARENT;
119 $item['object-type'] = ACTIVITY_OBJ_NOTE;
121 $item['gravity'] = GRAVITY_COMMENT;
122 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
125 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
126 logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
127 self::fetchMissingActivity($activity['reply-to-id'], $activity);
130 self::postItem($activity, $item);
134 * Prepare the item array for a "like"
136 * @param array $activity Activity array
138 public static function likeItem($activity)
141 $item['verb'] = ACTIVITY_LIKE;
142 $item['parent-uri'] = $activity['object_id'];
143 $item['gravity'] = GRAVITY_ACTIVITY;
144 $item['object-type'] = ACTIVITY_OBJ_NOTE;
146 self::postItem($activity, $item);
152 * @param array $activity
154 public static function deleteItem($activity)
156 $owner = Contact::getIdForURL($activity['actor']);
158 logger('Deleting item ' . $activity['object_id'] . ' from ' . $owner, LOGGER_DEBUG);
159 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
163 * Prepare the item array for a "dislike"
165 * @param array $activity Activity array
167 public static function dislikeItem($activity)
170 $item['verb'] = ACTIVITY_DISLIKE;
171 $item['parent-uri'] = $activity['object_id'];
172 $item['gravity'] = GRAVITY_ACTIVITY;
173 $item['object-type'] = ACTIVITY_OBJ_NOTE;
175 self::postItem($activity, $item);
179 * Creates an item post
181 * @param array $activity Activity data
182 * @param array $item item array
184 private static function postItem($activity, $item)
186 /// @todo What to do with $activity['context']?
188 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
189 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
193 $item['network'] = Protocol::ACTIVITYPUB;
194 $item['private'] = !in_array(0, $activity['receiver']);
195 $item['author-link'] = $activity['author'];
196 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
198 if (empty($activity['thread-completion'])) {
199 $item['owner-link'] = $activity['actor'];
200 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
202 logger('Ignoring actor because of thread completion.', LOGGER_DEBUG);
203 $item['owner-link'] = $item['author-link'];
204 $item['owner-id'] = $item['author-id'];
207 $item['uri'] = $activity['id'];
208 $item['created'] = $activity['published'];
209 $item['edited'] = $activity['updated'];
210 $item['guid'] = $activity['diaspora:guid'];
211 $item['title'] = HTML::toBBCode($activity['name']);
212 $item['content-warning'] = HTML::toBBCode($activity['summary']);
213 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
215 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
216 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
219 $item['location'] = $activity['location'];
221 if (!empty($item['latitude']) && !empty($item['longitude'])) {
222 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
225 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
226 $item['app'] = $activity['generator'];
227 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
228 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
230 $item = self::constructAttachList($activity['attachments'], $item);
232 if (!empty($activity['source'])) {
233 $item['body'] = $activity['source'];
236 foreach ($activity['receiver'] as $receiver) {
237 $item['uid'] = $receiver;
238 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
240 if (($receiver != 0) && empty($item['contact-id'])) {
241 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
244 $item_id = Item::insert($item);
245 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
250 * Fetches missing posts
255 private static function fetchMissingActivity($url, $child)
257 if (Config::get('system', 'ostatus_full_threads')) {
261 $object = ActivityPub::fetchContent($url);
262 if (empty($object)) {
263 logger('Activity ' . $url . ' was not fetchable, aborting.');
268 $activity['@context'] = $object['@context'];
269 unset($object['@context']);
270 $activity['id'] = $object['id'];
271 $activity['to'] = defaults($object, 'to', []);
272 $activity['cc'] = defaults($object, 'cc', []);
273 $activity['actor'] = $child['author'];
274 $activity['object'] = $object;
275 $activity['published'] = defaults($object, 'published', $child['published']);
276 $activity['type'] = 'Create';
278 $ldactivity = JsonLD::compact($activity);
280 $ldactivity['thread-completion'] = true;
282 ActivityPub\Receiver::processActivity($ldactivity);
283 logger('Activity ' . $url . ' had been fetched and processed.');
287 * perform a "follow" request
289 * @param array $activity
291 public static function followUser($activity)
293 $uid = User::getIdForURL($activity['object_id']);
298 $owner = User::getOwnerDataById($uid);
300 $cid = Contact::getIdForURL($activity['actor'], $uid);
302 self::switchContact($cid);
303 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
308 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
309 'author-link' => $activity['actor']];
311 // Ensure that the contact has got the right network type
312 self::switchContact($item['author-id']);
314 Contact::addRelationship($owner, $contact, $item);
315 $cid = Contact::getIdForURL($activity['actor'], $uid);
320 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
321 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
325 * Update the given profile
327 * @param array $activity
329 public static function updatePerson($activity)
331 if (empty($activity['object_id'])) {
335 logger('Updating profile for ' . $activity['object_id'], LOGGER_DEBUG);
336 APContact::getByURL($activity['object_id'], true);
340 * Delete the given profile
342 * @param array $activity
344 public static function deletePerson($activity)
346 if (empty($activity['object_id']) || empty($activity['actor'])) {
347 logger('Empty object id or actor.', LOGGER_DEBUG);
351 if ($activity['object_id'] != $activity['actor']) {
352 logger('Object id does not match actor.', LOGGER_DEBUG);
356 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object_id'])]);
357 while ($contact = DBA::fetch($contacts)) {
358 Contact::remove($contact['id']);
360 DBA::close($contacts);
362 logger('Deleted contact ' . $activity['object_id'], LOGGER_DEBUG);
366 * Accept a follow request
368 * @param array $activity
370 public static function acceptFollowUser($activity)
372 $uid = User::getIdForURL($activity['object_actor']);
377 $owner = User::getOwnerDataById($uid);
379 $cid = Contact::getIdForURL($activity['actor'], $uid);
381 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
385 self::switchContact($cid);
387 $fields = ['pending' => false];
389 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
390 if ($contact['rel'] == Contact::FOLLOWER) {
391 $fields['rel'] = Contact::FRIEND;
394 $condition = ['id' => $cid];
395 DBA::update('contact', $fields, $condition);
396 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
400 * Reject a follow request
402 * @param array $activity
404 public static function rejectFollowUser($activity)
406 $uid = User::getIdForURL($activity['object_actor']);
411 $owner = User::getOwnerDataById($uid);
413 $cid = Contact::getIdForURL($activity['actor'], $uid);
415 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
419 self::switchContact($cid);
421 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
422 Contact::remove($cid);
423 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
425 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
430 * Undo activity like "like" or "dislike"
432 * @param array $activity
434 public static function undoActivity($activity)
436 if (empty($activity['object_id'])) {
440 if (empty($activity['object_actor'])) {
444 $author_id = Contact::getIdForURL($activity['object_actor']);
445 if (empty($author_id)) {
449 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
453 * Activity to remove a follower
455 * @param array $activity
457 public static function undoFollowUser($activity)
459 $uid = User::getIdForURL($activity['object_object']);
464 $owner = User::getOwnerDataById($uid);
466 $cid = Contact::getIdForURL($activity['actor'], $uid);
468 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
472 self::switchContact($cid);
474 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
475 if (!DBA::isResult($contact)) {
479 Contact::removeFollower($owner, $contact);
480 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
484 * Switches a contact to AP if needed
486 * @param integer $cid Contact ID
488 private static function switchContact($cid)
490 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
491 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
495 logger('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
496 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);