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\Event;
14 use Friendica\Model\User;
15 use Friendica\Content\Text\HTML;
16 use Friendica\Util\JsonLD;
17 use Friendica\Core\Config;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
22 * ActivityPub Processor Protocol class
27 * Converts mentions from Pleroma into the Friendica format
31 * @return converted body
33 private static function convertMentions($body)
35 $URLSearchString = "^\[\]";
36 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
42 * Constructs a string with tags for a given tag array
45 * @param boolean $sensitive
47 * @return string with tags
49 private static function constructTagList($tags, $sensitive)
56 foreach ($tags as $tag) {
57 if (in_array(defaults($tag, 'type', ''), ['Mention', 'Hashtag'])) {
58 if (!empty($tag_text)) {
62 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
66 /// @todo add nsfw for $sensitive
72 * Add attachment data to the item array
74 * @param array $attachments
79 private static function constructAttachList($attachments, $item)
81 if (empty($attachments)) {
85 foreach ($attachments as $attach) {
86 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
87 if ($filetype == 'image') {
88 $item['body'] .= "\n[img]" . $attach['url'] . '[/img]';
90 if (!empty($item["attach"])) {
91 $item["attach"] .= ',';
95 if (!isset($attach['length'])) {
96 $attach['length'] = "0";
98 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
108 * @param array $activity Activity array
110 public static function updateItem($activity)
113 $item['changed'] = DateTimeFormat::utcNow();
114 $item['edited'] = $activity['updated'];
115 $item['title'] = HTML::toBBCode($activity['name']);
116 $item['content-warning'] = HTML::toBBCode($activity['summary']);
117 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
118 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
120 Item::update($item, ['uri' => $activity['id']]);
124 * Prepares data for a message
126 * @param array $activity Activity array
128 public static function createItem($activity)
131 $item['verb'] = ACTIVITY_POST;
132 $item['parent-uri'] = $activity['reply-to-id'];
134 if ($activity['reply-to-id'] == $activity['id']) {
135 $item['gravity'] = GRAVITY_PARENT;
136 $item['object-type'] = ACTIVITY_OBJ_NOTE;
138 $item['gravity'] = GRAVITY_COMMENT;
139 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
142 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
143 logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
144 self::fetchMissingActivity($activity['reply-to-id'], $activity);
147 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
149 self::postItem($activity, $item);
155 * @param array $activity
157 public static function deleteItem($activity)
159 $owner = Contact::getIdForURL($activity['actor']);
161 logger('Deleting item ' . $activity['object_id'] . ' from ' . $owner, LOGGER_DEBUG);
162 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
166 * Prepare the item array for an activity
168 * @param array $activity Activity array
169 * @param string $verb Activity verb
171 public static function createActivity($activity, $verb)
174 $item['verb'] = $verb;
175 $item['parent-uri'] = $activity['object_id'];
176 $item['gravity'] = GRAVITY_ACTIVITY;
177 $item['object-type'] = ACTIVITY_OBJ_NOTE;
179 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
181 self::postItem($activity, $item);
187 * @param array $activity Activity array
190 public static function createEvent($activity, $item)
192 $event['summary'] = $activity['name'];
193 $event['desc'] = $activity['content'];
194 $event['start'] = $activity['start-time'];
195 $event['finish'] = $activity['end-time'];
196 $event['nofinish'] = empty($event['finish']);
197 $event['location'] = $activity['location'];
198 $event['adjust'] = true;
199 $event['cid'] = $item['contact-id'];
200 $event['uid'] = $item['uid'];
201 $event['uri'] = $item['uri'];
202 $event['edited'] = $item['edited'];
203 $event['private'] = $item['private'];
204 $event['guid'] = $item['guid'];
205 $event['plink'] = $item['plink'];
207 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
208 $ev = DBA::selectFirst('event', ['id'], $condition);
209 if (DBA::isResult($ev)) {
210 $event['id'] = $ev['id'];
213 $event_id = Event::store($event);
214 logger('Event '.$event_id.' was stored', LOGGER_DEBUG);
218 * Creates an item post
220 * @param array $activity Activity data
221 * @param array $item item array
223 private static function postItem($activity, $item)
225 /// @todo What to do with $activity['context']?
227 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
228 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
232 $item['network'] = Protocol::ACTIVITYPUB;
233 $item['private'] = !in_array(0, $activity['receiver']);
234 $item['author-link'] = $activity['author'];
235 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
237 if (empty($activity['thread-completion'])) {
238 $item['owner-link'] = $activity['actor'];
239 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
241 logger('Ignoring actor because of thread completion.', LOGGER_DEBUG);
242 $item['owner-link'] = $item['author-link'];
243 $item['owner-id'] = $item['author-id'];
246 $item['uri'] = $activity['id'];
247 $item['created'] = $activity['published'];
248 $item['edited'] = $activity['updated'];
249 $item['guid'] = $activity['diaspora:guid'];
250 $item['title'] = HTML::toBBCode($activity['name']);
251 $item['content-warning'] = HTML::toBBCode($activity['summary']);
252 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
254 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
255 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
258 $item['location'] = $activity['location'];
260 if (!empty($item['latitude']) && !empty($item['longitude'])) {
261 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
264 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
265 $item['app'] = $activity['generator'];
266 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
268 $item = self::constructAttachList($activity['attachments'], $item);
270 if (!empty($activity['source'])) {
271 $item['body'] = $activity['source'];
274 foreach ($activity['receiver'] as $receiver) {
275 $item['uid'] = $receiver;
276 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
278 if (($receiver != 0) && empty($item['contact-id'])) {
279 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
282 if ($activity['object_type'] == 'as:Event') {
283 self::createEvent($activity, $item);
286 $item_id = Item::insert($item);
287 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
292 * Fetches missing posts
297 private static function fetchMissingActivity($url, $child)
299 if (Config::get('system', 'ostatus_full_threads')) {
303 $object = ActivityPub::fetchContent($url);
304 if (empty($object)) {
305 logger('Activity ' . $url . ' was not fetchable, aborting.');
310 $activity['@context'] = $object['@context'];
311 unset($object['@context']);
312 $activity['id'] = $object['id'];
313 $activity['to'] = defaults($object, 'to', []);
314 $activity['cc'] = defaults($object, 'cc', []);
315 $activity['actor'] = $child['author'];
316 $activity['object'] = $object;
317 $activity['published'] = defaults($object, 'published', $child['published']);
318 $activity['type'] = 'Create';
320 $ldactivity = JsonLD::compact($activity);
322 $ldactivity['thread-completion'] = true;
324 ActivityPub\Receiver::processActivity($ldactivity);
325 logger('Activity ' . $url . ' had been fetched and processed.');
329 * perform a "follow" request
331 * @param array $activity
333 public static function followUser($activity)
335 $uid = User::getIdForURL($activity['object_id']);
340 $owner = User::getOwnerDataById($uid);
342 $cid = Contact::getIdForURL($activity['actor'], $uid);
344 self::switchContact($cid);
345 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
350 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
351 'author-link' => $activity['actor']];
353 // Ensure that the contact has got the right network type
354 self::switchContact($item['author-id']);
356 Contact::addRelationship($owner, $contact, $item);
357 $cid = Contact::getIdForURL($activity['actor'], $uid);
362 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
363 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
367 * Update the given profile
369 * @param array $activity
371 public static function updatePerson($activity)
373 if (empty($activity['object_id'])) {
377 logger('Updating profile for ' . $activity['object_id'], LOGGER_DEBUG);
378 APContact::getByURL($activity['object_id'], true);
382 * Delete the given profile
384 * @param array $activity
386 public static function deletePerson($activity)
388 if (empty($activity['object_id']) || empty($activity['actor'])) {
389 logger('Empty object id or actor.', LOGGER_DEBUG);
393 if ($activity['object_id'] != $activity['actor']) {
394 logger('Object id does not match actor.', LOGGER_DEBUG);
398 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object_id'])]);
399 while ($contact = DBA::fetch($contacts)) {
400 Contact::remove($contact['id']);
402 DBA::close($contacts);
404 logger('Deleted contact ' . $activity['object_id'], LOGGER_DEBUG);
408 * Accept a follow request
410 * @param array $activity
412 public static function acceptFollowUser($activity)
414 $uid = User::getIdForURL($activity['object_actor']);
419 $owner = User::getOwnerDataById($uid);
421 $cid = Contact::getIdForURL($activity['actor'], $uid);
423 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
427 self::switchContact($cid);
429 $fields = ['pending' => false];
431 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
432 if ($contact['rel'] == Contact::FOLLOWER) {
433 $fields['rel'] = Contact::FRIEND;
436 $condition = ['id' => $cid];
437 DBA::update('contact', $fields, $condition);
438 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
442 * Reject a follow request
444 * @param array $activity
446 public static function rejectFollowUser($activity)
448 $uid = User::getIdForURL($activity['object_actor']);
453 $owner = User::getOwnerDataById($uid);
455 $cid = Contact::getIdForURL($activity['actor'], $uid);
457 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
461 self::switchContact($cid);
463 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
464 Contact::remove($cid);
465 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
467 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
472 * Undo activity like "like" or "dislike"
474 * @param array $activity
476 public static function undoActivity($activity)
478 if (empty($activity['object_id'])) {
482 if (empty($activity['object_actor'])) {
486 $author_id = Contact::getIdForURL($activity['object_actor']);
487 if (empty($author_id)) {
491 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
495 * Activity to remove a follower
497 * @param array $activity
499 public static function undoFollowUser($activity)
501 $uid = User::getIdForURL($activity['object_object']);
506 $owner = User::getOwnerDataById($uid);
508 $cid = Contact::getIdForURL($activity['actor'], $uid);
510 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
514 self::switchContact($cid);
516 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
517 if (!DBA::isResult($contact)) {
521 Contact::removeFollower($owner, $contact);
522 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
526 * Switches a contact to AP if needed
528 * @param integer $cid Contact ID
530 private static function switchContact($cid)
532 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
533 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
537 logger('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
538 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);