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 self::postItem($activity, $item);
153 * @param array $activity
155 public static function deleteItem($activity)
157 $owner = Contact::getIdForURL($activity['actor']);
159 logger('Deleting item ' . $activity['object_id'] . ' from ' . $owner, LOGGER_DEBUG);
160 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
164 * Prepare the item array for an activity
166 * @param array $activity Activity array
167 * @param string $verb Activity verb
169 public static function createActivity($activity, $verb)
172 $item['verb'] = $verb;
173 $item['parent-uri'] = $activity['object_id'];
174 $item['gravity'] = GRAVITY_ACTIVITY;
175 $item['object-type'] = ACTIVITY_OBJ_NOTE;
177 self::postItem($activity, $item);
183 * @param array $activity Activity array
186 public static function createEvent($activity, $item)
188 $event['summary'] = $activity['name'];
189 $event['desc'] = $activity['content'];
190 $event['start'] = $activity['start-time'];
191 $event['finish'] = $activity['end-time'];
192 $event['nofinish'] = empty($event['finish']);
193 $event['location'] = $activity['location'];
194 $event['adjust'] = true;
195 $event['cid'] = $item['contact-id'];
196 $event['uid'] = $item['uid'];
197 $event['uri'] = $item['uri'];
198 $event['edited'] = $item['edited'];
199 $event['private'] = $item['private'];
200 $event['guid'] = $item['guid'];
201 $event['plink'] = $item['plink'];
203 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
204 $ev = DBA::selectFirst('event', ['id'], $condition);
205 if (DBA::isResult($ev)) {
206 $event['id'] = $ev['id'];
209 $event_id = Event::store($event);
210 logger('Event '.$event_id.' was stored', LOGGER_DEBUG);
214 * Creates an item post
216 * @param array $activity Activity data
217 * @param array $item item array
219 private static function postItem($activity, $item)
221 /// @todo What to do with $activity['context']?
223 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
224 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
228 $item['network'] = Protocol::ACTIVITYPUB;
229 $item['private'] = !in_array(0, $activity['receiver']);
230 $item['author-link'] = $activity['author'];
231 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
233 if (empty($activity['thread-completion'])) {
234 $item['owner-link'] = $activity['actor'];
235 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
237 logger('Ignoring actor because of thread completion.', LOGGER_DEBUG);
238 $item['owner-link'] = $item['author-link'];
239 $item['owner-id'] = $item['author-id'];
242 $item['uri'] = $activity['id'];
243 $item['created'] = $activity['published'];
244 $item['edited'] = $activity['updated'];
245 $item['guid'] = $activity['diaspora:guid'];
246 $item['title'] = HTML::toBBCode($activity['name']);
247 $item['content-warning'] = HTML::toBBCode($activity['summary']);
248 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
250 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
251 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
254 $item['location'] = $activity['location'];
256 if (!empty($item['latitude']) && !empty($item['longitude'])) {
257 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
260 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
261 $item['app'] = $activity['generator'];
262 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
263 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
265 $item = self::constructAttachList($activity['attachments'], $item);
267 if (!empty($activity['source'])) {
268 $item['body'] = $activity['source'];
271 foreach ($activity['receiver'] as $receiver) {
272 $item['uid'] = $receiver;
273 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
275 if (($receiver != 0) && empty($item['contact-id'])) {
276 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
279 if ($activity['object_type'] == 'as:Event') {
280 self::createEvent($activity, $item);
283 $item_id = Item::insert($item);
284 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
289 * Fetches missing posts
294 private static function fetchMissingActivity($url, $child)
296 if (Config::get('system', 'ostatus_full_threads')) {
300 $object = ActivityPub::fetchContent($url);
301 if (empty($object)) {
302 logger('Activity ' . $url . ' was not fetchable, aborting.');
307 $activity['@context'] = $object['@context'];
308 unset($object['@context']);
309 $activity['id'] = $object['id'];
310 $activity['to'] = defaults($object, 'to', []);
311 $activity['cc'] = defaults($object, 'cc', []);
312 $activity['actor'] = $child['author'];
313 $activity['object'] = $object;
314 $activity['published'] = defaults($object, 'published', $child['published']);
315 $activity['type'] = 'Create';
317 $ldactivity = JsonLD::compact($activity);
319 $ldactivity['thread-completion'] = true;
321 ActivityPub\Receiver::processActivity($ldactivity);
322 logger('Activity ' . $url . ' had been fetched and processed.');
326 * perform a "follow" request
328 * @param array $activity
330 public static function followUser($activity)
332 $uid = User::getIdForURL($activity['object_id']);
337 $owner = User::getOwnerDataById($uid);
339 $cid = Contact::getIdForURL($activity['actor'], $uid);
341 self::switchContact($cid);
342 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
347 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
348 'author-link' => $activity['actor']];
350 // Ensure that the contact has got the right network type
351 self::switchContact($item['author-id']);
353 Contact::addRelationship($owner, $contact, $item);
354 $cid = Contact::getIdForURL($activity['actor'], $uid);
359 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
360 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
364 * Update the given profile
366 * @param array $activity
368 public static function updatePerson($activity)
370 if (empty($activity['object_id'])) {
374 logger('Updating profile for ' . $activity['object_id'], LOGGER_DEBUG);
375 APContact::getByURL($activity['object_id'], true);
379 * Delete the given profile
381 * @param array $activity
383 public static function deletePerson($activity)
385 if (empty($activity['object_id']) || empty($activity['actor'])) {
386 logger('Empty object id or actor.', LOGGER_DEBUG);
390 if ($activity['object_id'] != $activity['actor']) {
391 logger('Object id does not match actor.', LOGGER_DEBUG);
395 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object_id'])]);
396 while ($contact = DBA::fetch($contacts)) {
397 Contact::remove($contact['id']);
399 DBA::close($contacts);
401 logger('Deleted contact ' . $activity['object_id'], LOGGER_DEBUG);
405 * Accept a follow request
407 * @param array $activity
409 public static function acceptFollowUser($activity)
411 $uid = User::getIdForURL($activity['object_actor']);
416 $owner = User::getOwnerDataById($uid);
418 $cid = Contact::getIdForURL($activity['actor'], $uid);
420 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
424 self::switchContact($cid);
426 $fields = ['pending' => false];
428 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
429 if ($contact['rel'] == Contact::FOLLOWER) {
430 $fields['rel'] = Contact::FRIEND;
433 $condition = ['id' => $cid];
434 DBA::update('contact', $fields, $condition);
435 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
439 * Reject a follow request
441 * @param array $activity
443 public static function rejectFollowUser($activity)
445 $uid = User::getIdForURL($activity['object_actor']);
450 $owner = User::getOwnerDataById($uid);
452 $cid = Contact::getIdForURL($activity['actor'], $uid);
454 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
458 self::switchContact($cid);
460 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
461 Contact::remove($cid);
462 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
464 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
469 * Undo activity like "like" or "dislike"
471 * @param array $activity
473 public static function undoActivity($activity)
475 if (empty($activity['object_id'])) {
479 if (empty($activity['object_actor'])) {
483 $author_id = Contact::getIdForURL($activity['object_actor']);
484 if (empty($author_id)) {
488 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
492 * Activity to remove a follower
494 * @param array $activity
496 public static function undoFollowUser($activity)
498 $uid = User::getIdForURL($activity['object_object']);
503 $owner = User::getOwnerDataById($uid);
505 $cid = Contact::getIdForURL($activity['actor'], $uid);
507 logger('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
511 self::switchContact($cid);
513 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
514 if (!DBA::isResult($contact)) {
518 Contact::removeFollower($owner, $contact);
519 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
523 * Switches a contact to AP if needed
525 * @param integer $cid Contact ID
527 private static function switchContact($cid)
529 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
530 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
534 logger('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
535 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);