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 * 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]';
109 * @param array $activity Activity array
111 public static function updateItem($activity)
114 $item['changed'] = DateTimeFormat::utcNow();
115 $item['edited'] = $activity['updated'];
116 $item['title'] = HTML::toBBCode($activity['name']);
117 $item['content-warning'] = HTML::toBBCode($activity['summary']);
118 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
119 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
121 Item::update($item, ['uri' => $activity['id']]);
125 * Prepares data for a message
127 * @param array $activity Activity array
129 public static function createItem($activity)
132 $item['verb'] = ACTIVITY_POST;
133 $item['parent-uri'] = $activity['reply-to-id'];
135 if ($activity['reply-to-id'] == $activity['id']) {
136 $item['gravity'] = GRAVITY_PARENT;
137 $item['object-type'] = ACTIVITY_OBJ_NOTE;
139 $item['gravity'] = GRAVITY_COMMENT;
140 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
143 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
144 Logger::log('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
145 self::fetchMissingActivity($activity['reply-to-id'], $activity);
148 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:comment', '');
150 self::postItem($activity, $item);
156 * @param array $activity
158 public static function deleteItem($activity)
160 $owner = Contact::getIdForURL($activity['actor']);
162 Logger::log('Deleting item ' . $activity['object_id'] . ' from ' . $owner, LOGGER_DEBUG);
163 Item::delete(['uri' => $activity['object_id'], 'owner-id' => $owner]);
167 * Prepare the item array for an activity
169 * @param array $activity Activity array
170 * @param string $verb Activity verb
172 public static function createActivity($activity, $verb)
175 $item['verb'] = $verb;
176 $item['parent-uri'] = $activity['object_id'];
177 $item['gravity'] = GRAVITY_ACTIVITY;
178 $item['object-type'] = ACTIVITY_OBJ_NOTE;
180 $item['diaspora_signed_text'] = defaults($activity, 'diaspora:like', '');
182 self::postItem($activity, $item);
188 * @param array $activity Activity array
191 public static function createEvent($activity, $item)
193 $event['summary'] = $activity['name'];
194 $event['desc'] = $activity['content'];
195 $event['start'] = $activity['start-time'];
196 $event['finish'] = $activity['end-time'];
197 $event['nofinish'] = empty($event['finish']);
198 $event['location'] = $activity['location'];
199 $event['adjust'] = true;
200 $event['cid'] = $item['contact-id'];
201 $event['uid'] = $item['uid'];
202 $event['uri'] = $item['uri'];
203 $event['edited'] = $item['edited'];
204 $event['private'] = $item['private'];
205 $event['guid'] = $item['guid'];
206 $event['plink'] = $item['plink'];
208 $condition = ['uri' => $item['uri'], 'uid' => $item['uid']];
209 $ev = DBA::selectFirst('event', ['id'], $condition);
210 if (DBA::isResult($ev)) {
211 $event['id'] = $ev['id'];
214 $event_id = Event::store($event);
215 Logger::log('Event '.$event_id.' was stored', LOGGER_DEBUG);
219 * Creates an item post
221 * @param array $activity Activity data
222 * @param array $item item array
224 private static function postItem($activity, $item)
226 /// @todo What to do with $activity['context']?
228 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
229 Logger::log('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
233 $item['network'] = Protocol::ACTIVITYPUB;
234 $item['private'] = !in_array(0, $activity['receiver']);
235 $item['author-link'] = $activity['author'];
236 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
238 if (empty($activity['thread-completion'])) {
239 $item['owner-link'] = $activity['actor'];
240 $item['owner-id'] = Contact::getIdForURL($activity['actor'], 0, true);
242 Logger::log('Ignoring actor because of thread completion.', LOGGER_DEBUG);
243 $item['owner-link'] = $item['author-link'];
244 $item['owner-id'] = $item['author-id'];
247 $item['uri'] = $activity['id'];
248 $item['created'] = $activity['published'];
249 $item['edited'] = $activity['updated'];
250 $item['guid'] = $activity['diaspora:guid'];
251 $item['title'] = HTML::toBBCode($activity['name']);
252 $item['content-warning'] = HTML::toBBCode($activity['summary']);
253 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
255 if (($activity['object_type'] == 'as:Video') && !empty($activity['alternate-url'])) {
256 $item['body'] .= "\n[video]" . $activity['alternate-url'] . '[/video]';
259 $item['location'] = $activity['location'];
261 if (!empty($item['latitude']) && !empty($item['longitude'])) {
262 $item['coord'] = $item['latitude'] . ' ' . $item['longitude'];
265 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
266 $item['app'] = $activity['generator'];
267 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
269 $item = self::constructAttachList($activity['attachments'], $item);
271 if (!empty($activity['source'])) {
272 $item['body'] = $activity['source'];
275 foreach ($activity['receiver'] as $receiver) {
276 $item['uid'] = $receiver;
277 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
279 if (($receiver != 0) && empty($item['contact-id'])) {
280 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
283 if ($activity['object_type'] == 'as:Event') {
284 self::createEvent($activity, $item);
287 $item_id = Item::insert($item);
288 Logger::log('Storing for user ' . $item['uid'] . ': ' . $item_id);
293 * Fetches missing posts
298 private static function fetchMissingActivity($url, $child)
300 if (Config::get('system', 'ostatus_full_threads')) {
304 $object = ActivityPub::fetchContent($url);
305 if (empty($object)) {
306 Logger::log('Activity ' . $url . ' was not fetchable, aborting.');
311 $activity['@context'] = $object['@context'];
312 unset($object['@context']);
313 $activity['id'] = $object['id'];
314 $activity['to'] = defaults($object, 'to', []);
315 $activity['cc'] = defaults($object, 'cc', []);
316 $activity['actor'] = $child['author'];
317 $activity['object'] = $object;
318 $activity['published'] = defaults($object, 'published', $child['published']);
319 $activity['type'] = 'Create';
321 $ldactivity = JsonLD::compact($activity);
323 $ldactivity['thread-completion'] = true;
325 ActivityPub\Receiver::processActivity($ldactivity);
326 Logger::log('Activity ' . $url . ' had been fetched and processed.');
330 * perform a "follow" request
332 * @param array $activity
334 public static function followUser($activity)
336 $uid = User::getIdForURL($activity['object_id']);
341 $owner = User::getOwnerDataById($uid);
343 $cid = Contact::getIdForURL($activity['actor'], $uid);
345 self::switchContact($cid);
346 $contact = DBA::selectFirst('contact', [], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
351 $item = ['author-id' => Contact::getIdForURL($activity['actor']),
352 'author-link' => $activity['actor']];
354 // Ensure that the contact has got the right network type
355 self::switchContact($item['author-id']);
357 Contact::addRelationship($owner, $contact, $item);
358 $cid = Contact::getIdForURL($activity['actor'], $uid);
363 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
364 Logger::log('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
368 * Update the given profile
370 * @param array $activity
372 public static function updatePerson($activity)
374 if (empty($activity['object_id'])) {
378 Logger::log('Updating profile for ' . $activity['object_id'], LOGGER_DEBUG);
379 APContact::getByURL($activity['object_id'], true);
383 * Delete the given profile
385 * @param array $activity
387 public static function deletePerson($activity)
389 if (empty($activity['object_id']) || empty($activity['actor'])) {
390 Logger::log('Empty object id or actor.', LOGGER_DEBUG);
394 if ($activity['object_id'] != $activity['actor']) {
395 Logger::log('Object id does not match actor.', LOGGER_DEBUG);
399 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object_id'])]);
400 while ($contact = DBA::fetch($contacts)) {
401 Contact::remove($contact['id']);
403 DBA::close($contacts);
405 Logger::log('Deleted contact ' . $activity['object_id'], LOGGER_DEBUG);
409 * Accept a follow request
411 * @param array $activity
413 public static function acceptFollowUser($activity)
415 $uid = User::getIdForURL($activity['object_actor']);
420 $owner = User::getOwnerDataById($uid);
422 $cid = Contact::getIdForURL($activity['actor'], $uid);
424 Logger::log('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
428 self::switchContact($cid);
430 $fields = ['pending' => false];
432 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
433 if ($contact['rel'] == Contact::FOLLOWER) {
434 $fields['rel'] = Contact::FRIEND;
437 $condition = ['id' => $cid];
438 DBA::update('contact', $fields, $condition);
439 Logger::log('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
443 * Reject a follow request
445 * @param array $activity
447 public static function rejectFollowUser($activity)
449 $uid = User::getIdForURL($activity['object_actor']);
454 $owner = User::getOwnerDataById($uid);
456 $cid = Contact::getIdForURL($activity['actor'], $uid);
458 Logger::log('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
462 self::switchContact($cid);
464 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
465 Contact::remove($cid);
466 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
468 Logger::log('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
473 * Undo activity like "like" or "dislike"
475 * @param array $activity
477 public static function undoActivity($activity)
479 if (empty($activity['object_id'])) {
483 if (empty($activity['object_actor'])) {
487 $author_id = Contact::getIdForURL($activity['object_actor']);
488 if (empty($author_id)) {
492 Item::delete(['uri' => $activity['object_id'], 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
496 * Activity to remove a follower
498 * @param array $activity
500 public static function undoFollowUser($activity)
502 $uid = User::getIdForURL($activity['object_object']);
507 $owner = User::getOwnerDataById($uid);
509 $cid = Contact::getIdForURL($activity['actor'], $uid);
511 Logger::log('No contact found for ' . $activity['actor'], LOGGER_DEBUG);
515 self::switchContact($cid);
517 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
518 if (!DBA::isResult($contact)) {
522 Contact::removeFollower($owner, $contact);
523 Logger::log('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
527 * Switches a contact to AP if needed
529 * @param integer $cid Contact ID
531 private static function switchContact($cid)
533 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid, 'network' => Protocol::NATIVE_SUPPORT]);
534 if (!DBA::isResult($contact) || ($contact['network'] == Protocol::ACTIVITYPUB)) {
538 Logger::log('Change existing contact ' . $cid . ' from ' . $contact['network'] . ' to ActivityPub.');
539 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);