3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
32 use Friendica\Model\Contact;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Util\HTTPSignature;
40 use Friendica\Util\JsonLD;
41 use Friendica\Util\LDSignature;
42 use Friendica\Util\Strings;
45 * ActivityPub Receiver Protocol class
50 * Check what this is meant to do:
59 const PUBLIC_COLLECTION = 'as:Public';
60 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
61 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
62 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
64 const TARGET_UNKNOWN = 0;
69 const TARGET_FOLLOWER = 5;
70 const TARGET_ANSWER = 6;
71 const TARGET_GLOBAL = 7;
73 const COMPLETION_NONE = 0;
74 const COMPLETION_ANNOUCE = 1;
75 const COMPLETION_RELAY = 2;
76 const COMPLETION_MANUAL = 3;
77 const COMPLETION_AUTO = 4;
80 * Checks incoming message from the inbox
84 * @param integer $uid User ID
87 public static function processInbox($body, $header, $uid)
89 $activity = json_decode($body, true);
90 if (empty($activity)) {
91 Logger::warning('Invalid body.');
95 $ldactivity = JsonLD::compact($activity);
97 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
99 $apcontact = APContact::getByURL($actor);
100 if (empty($apcontact)) {
101 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
103 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
104 self::processRelayPost($ldactivity, $actor);
107 APContact::unmarkForArchival($apcontact);
110 $http_signer = HTTPSignature::getSigner($body, $header);
111 if ($http_signer === false) {
112 Logger::warning('Invalid HTTP signature, message will be discarded.');
114 } elseif (empty($http_signer)) {
115 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
118 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
121 $signer = [$http_signer];
123 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
125 if (LDSignature::isSigned($activity)) {
126 $ld_signer = LDSignature::getSigner($activity);
127 if (empty($ld_signer)) {
128 Logger::info('Invalid JSON-LD signature from ' . $actor);
129 } elseif ($ld_signer != $http_signer) {
130 $signer[] = $ld_signer;
132 if (!empty($ld_signer && ($actor == $http_signer))) {
133 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
134 $trust_source = true;
135 } elseif (!empty($ld_signer)) {
136 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
137 $trust_source = true;
138 } elseif ($actor == $http_signer) {
139 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
140 $trust_source = true;
142 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
143 $trust_source = false;
145 } elseif ($actor == $http_signer) {
146 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
147 $trust_source = true;
149 Logger::info('No JSON-LD signature, different actor.');
150 $trust_source = false;
153 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
157 * Process incoming posts from relays
159 * @param array $activity
160 * @param string $actor
163 private static function processRelayPost(array $activity, string $actor)
165 $type = JsonLD::fetchElement($activity, '@type');
167 Logger::info('Empty type', ['activity' => $activity]);
171 if ($type != 'as:Announce') {
172 Logger::info('Not an announcement', ['activity' => $activity]);
176 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
177 if (empty($object_id)) {
178 Logger::info('No object id found', ['activity' => $activity]);
182 $contact = Contact::getByURL($actor);
183 if (empty($contact)) {
184 Logger::info('Relay contact not found', ['actor' => $actor]);
188 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
189 Logger::notice('Relay is no sharer', ['actor' => $actor]);
193 Logger::info('Got relayed message id', ['id' => $object_id]);
195 $item_id = Item::searchByLink($object_id);
197 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
201 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
203 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
207 $item_id = Item::searchByLink($object_id);
209 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
211 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
216 * Fetches the object type for a given object id
218 * @param array $activity
219 * @param string $object_id Object ID of the the provided object
220 * @param integer $uid User ID
222 * @return string with object type
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224 * @throws \ImagickException
226 private static function fetchObjectType($activity, $object_id, $uid = 0)
228 if (!empty($activity['as:object'])) {
229 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
230 if (!empty($object_type)) {
235 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
236 // We just assume "note" since it doesn't make a difference for the further processing
240 $profile = APContact::getByURL($object_id);
241 if (!empty($profile['type'])) {
242 APContact::unmarkForArchival($profile);
243 return 'as:' . $profile['type'];
246 $data = ActivityPub::fetchContent($object_id, $uid);
248 $object = JsonLD::compact($data);
249 $type = JsonLD::fetchElement($object, '@type');
259 * Prepare the object array
261 * @param array $activity Array with activity data
262 * @param integer $uid User ID
263 * @param boolean $push Message had been pushed to our system
264 * @param boolean $trust_source Do we trust the source?
266 * @return array with object data
267 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 * @throws \ImagickException
270 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
272 $id = JsonLD::fetchElement($activity, '@id');
273 if (!empty($id) && !$trust_source) {
274 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
276 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
277 if (!empty($fetched_activity)) {
278 $object = JsonLD::compact($fetched_activity);
279 $fetched_id = JsonLD::fetchElement($object, '@id');
280 if ($fetched_id == $id) {
281 Logger::info('Activity had been fetched successfully', ['id' => $id]);
282 $trust_source = true;
285 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
288 Logger::info('Activity could not been fetched', ['id' => $id]);
292 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
294 Logger::info('Empty actor', ['activity' => $activity]);
298 $type = JsonLD::fetchElement($activity, '@type');
300 // Fetch all receivers from to, cc, bto and bcc
301 $receiverdata = self::getReceivers($activity, $actor);
302 $receivers = $reception_types = [];
303 foreach ($receiverdata as $key => $data) {
304 $receivers[$key] = $data['uid'];
305 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
308 $urls = self::getReceiverURL($activity);
310 // When it is a delivery to a personal inbox we add that user to the receivers
312 $additional = [$uid => $uid];
313 $receivers = array_replace($receivers, $additional);
314 if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
315 $reception_types[$uid] = self::TARGET_BCC;
316 $owner = User::getOwnerDataById($uid);
317 if (!empty($owner['url'])) {
318 $urls['as:bcc'][] = $owner['url'];
323 // We possibly need some user to fetch private content,
324 // so we fetch one out of the receivers if no uid is provided.
325 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
327 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
328 if (empty($object_id)) {
329 Logger::info('No object found');
333 if (!is_string($object_id)) {
334 Logger::info('Invalid object id', ['object' => $object_id]);
338 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
340 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
341 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
342 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
344 $type = $object_type;
345 $activity = JsonLD::compact($data);
347 // Some variables need to be refetched since the activity changed
348 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
349 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
350 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
354 // Any activities on account types must not be altered
355 if (in_array($object_type, self::ACCOUNT_TYPES)) {
357 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
358 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
359 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
360 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
361 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
362 $object_data['push'] = $push;
363 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
364 // Fetch the content only on activities where this matters
365 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
366 // Always fetch on "Announce"
367 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
368 if (empty($object_data)) {
369 Logger::info("Object data couldn't be processed");
373 $object_data['object_id'] = $object_id;
375 if ($type == 'as:Announce') {
376 $object_data['push'] = false;
378 $object_data['push'] = $push;
381 // Test if it is an answer to a mail
382 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
383 $object_data['directmessage'] = true;
385 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
387 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
388 // Create a mostly empty array out of the activity data (instead of the object).
389 // This way we later don't have to check for the existence of each individual array element.
390 $object_data = self::processObject($activity);
391 $object_data['name'] = $type;
392 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
393 $object_data['object_id'] = $object_id;
394 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
395 $object_data['push'] = $push;
396 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
398 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
399 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
400 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
401 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
402 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
403 $object_data['push'] = $push;
406 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
407 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
408 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
409 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
410 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
411 $object_data['push'] = $push;
413 // An Undo is done on the object of an object, so we need that type as well
414 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
415 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
419 $object_data = self::addActivityFields($object_data, $activity);
421 if (empty($object_data['object_type'])) {
422 $object_data['object_type'] = $object_type;
425 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
426 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
427 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
431 $object_data['type'] = $type;
432 $object_data['actor'] = $actor;
433 $object_data['item_receiver'] = $receivers;
434 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
435 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
437 $author = $object_data['author'] ?? $actor;
438 if (!empty($author) && !empty($object_data['id'])) {
439 $author_host = parse_url($author, PHP_URL_HOST);
440 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
441 if ($author_host == $id_host) {
442 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
444 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
445 $trust_source = false;
449 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
455 * Fetches the first user id from the receiver array
457 * @param array $receivers Array with receivers
458 * @return integer user id;
460 public static function getFirstUserFromReceivers($receivers)
462 foreach ($receivers as $receiver) {
463 if (!empty($receiver)) {
471 * Processes the activity object
473 * @param array $activity Array with activity data
474 * @param string $body The unprocessed body
475 * @param integer $uid User ID
476 * @param boolean $trust_source Do we trust the source?
477 * @param boolean $push Message had been pushed to our system
478 * @param array $signer The signer of the post
481 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
483 $type = JsonLD::fetchElement($activity, '@type');
485 Logger::info('Empty type', ['activity' => $activity]);
489 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
490 Logger::info('Empty object', ['activity' => $activity]);
494 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
496 Logger::info('Empty actor', ['activity' => $activity]);
500 if (is_array($activity['as:object'])) {
501 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
506 // Test the provided signatures against the actor and "attributedTo"
508 if (!empty($attributed_to) && !empty($actor)) {
509 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
511 $trust_source = in_array($actor, $signer);
515 // $trust_source is called by reference and is set to true if the content was retrieved successfully
516 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
517 if (empty($object_data)) {
518 Logger::info('No object data found', ['activity' => $activity]);
522 // Lemmy is announcing activities.
523 // We are changing the announces into regular activities.
524 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
525 $type = $object_data['type'];
528 if (!$trust_source) {
529 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
533 if (!empty($body) && empty($object_data['raw'])) {
534 $object_data['raw'] = $body;
537 // Internal flag for thread completion. See Processor.php
538 if (!empty($activity['thread-completion'])) {
539 $object_data['thread-completion'] = $activity['thread-completion'];
542 if (!empty($activity['completion-mode'])) {
543 $object_data['completion-mode'] = $activity['completion-mode'];
546 if (!empty($activity['thread-children-type'])) {
547 $object_data['thread-children-type'] = $activity['thread-children-type'];
550 // Internal flag for posts that arrived via relay
551 if (!empty($activity['from-relay'])) {
552 $object_data['from-relay'] = $activity['from-relay'];
557 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
558 $item = ActivityPub\Processor::createItem($object_data);
559 ActivityPub\Processor::postItem($object_data, $item);
560 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
561 // Unhandled Peertube activity
563 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
568 if (in_array($object_data['object_type'], ['as:Event'])) {
569 $item = ActivityPub\Processor::createItem($object_data);
570 ActivityPub\Processor::postItem($object_data, $item);
572 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
577 if ($object_data['object_type'] == 'as:tag') {
578 ActivityPub\Processor::addTag($object_data);
579 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
580 // Seems to be used by Mastodon to announce that a post is pinned
581 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
582 } elseif ($object_data['object_type'] == '') {
583 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
585 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
590 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
591 $object_data['thread-completion'] = Contact::getIdForURL($actor);
592 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
594 $item = ActivityPub\Processor::createItem($object_data);
599 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
600 ActivityPub\Processor::postItem($object_data, $item);
602 $announce_object_data = self::processObject($activity);
603 $announce_object_data['name'] = $type;
604 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
605 $announce_object_data['object_id'] = $object_data['object_id'];
606 $announce_object_data['object_type'] = $object_data['object_type'];
607 $announce_object_data['push'] = $push;
610 $announce_object_data['raw'] = $body;
613 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
615 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
620 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
621 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
622 } elseif ($object_data['object_type'] == '') {
623 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
625 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
630 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
631 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
632 } elseif ($object_data['object_type'] == '') {
633 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
635 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
639 case 'as:TentativeAccept':
640 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
641 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
643 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
648 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
649 ActivityPub\Processor::updateItem($object_data);
650 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
651 ActivityPub\Processor::updatePerson($object_data);
652 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
653 // Unhandled Peertube activity
655 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
660 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
661 ActivityPub\Processor::deleteItem($object_data);
662 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
663 ActivityPub\Processor::deletePerson($object_data);
664 } elseif ($object_data['object_type'] == '') {
665 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
667 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
672 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
673 // Used by Mastodon to announce that the sender has blocked the account
674 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
676 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
681 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
682 // Seems to be used by Mastodon to remove the pinned status of a post
683 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
684 } elseif ($object_data['object_type'] == '') {
685 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
687 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
692 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
693 ActivityPub\Processor::followUser($object_data);
694 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
695 $object_data['reply-to-id'] = $object_data['object_id'];
696 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
698 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
703 if ($object_data['object_type'] == 'as:Follow') {
704 ActivityPub\Processor::acceptFollowUser($object_data);
705 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
706 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
708 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
713 if ($object_data['object_type'] == 'as:Follow') {
714 ActivityPub\Processor::rejectFollowUser($object_data);
715 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
716 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
718 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
723 if (($object_data['object_type'] == 'as:Follow') &&
724 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
725 ActivityPub\Processor::undoFollowUser($object_data);
726 } elseif (($object_data['object_type'] == 'as:Follow') &&
727 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
728 ActivityPub\Processor::undoActivity($object_data);
729 } elseif (($object_data['object_type'] == 'as:Accept') &&
730 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
731 ActivityPub\Processor::rejectFollowUser($object_data);
732 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
733 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
734 ActivityPub\Processor::undoActivity($object_data);
735 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
736 empty($object_data['object_object_type'])) {
737 // We cannot detect the target object. So we can ignore it.
738 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
739 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
740 // Unhandled Peertube activity
742 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
747 if (in_array($object_data['object_type'], ['as:Note', 'as:Video'])) {
748 // Unhandled Peertube activity
750 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
754 case 'litepub:EmojiReact':
755 if (in_array($object_data['object_type'], array_merge([''], self::CONTENT_TYPES))) {
756 // Unhandled Pleroma activity to react to a post via an emoji
758 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
763 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
764 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
770 * Stores unhandled or unknown Activitities as a file
772 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
773 * @param string $type Activity type
774 * @param array $object_data Preprocessed array that is generated out of the received activity
775 * @param array $activity Array with activity data
776 * @param string $body The unprocessed body
777 * @param integer $uid User ID
778 * @param boolean $trust_source Do we trust the source?
779 * @param boolean $push Message had been pushed to our system
780 * @param array $signer The signer of the post
783 private static function storeUnhandledActivity(bool $unknown, string $type, array $object_data, array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
785 if (!DI::config()->get('debug', 'ap_log_unknown')) {
789 $tempfile = tempnam(System::getTempPath(), ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-' . str_replace(':', '-', $object_data['object_type']) . '-' . str_replace(':', '-', $object_data['object_object_type'] ?? '') . '-');
790 file_put_contents($tempfile, json_encode(['activity' => $activity, 'body' => $body, 'uid' => $uid, 'trust_source' => $trust_source, 'push' => $push, 'signer' => $signer, 'object_data' => $object_data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
791 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
795 * Fetch a user id from an activity array
797 * @param array $activity
798 * @param string $actor
800 * @return int user id
802 public static function getBestUserForActivity(array $activity)
805 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
807 $receivers = self::getReceivers($activity, $actor);
808 foreach ($receivers as $receiver) {
809 if ($receiver['type'] == self::TARGET_GLOBAL) {
812 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
813 $uid = $receiver['uid'];
817 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
819 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
820 if (!empty($contact['uid'])) {
821 $uid = $contact['uid'];
828 public static function getReceiverURL($activity)
832 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
833 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
834 if (empty($receiver_list)) {
838 foreach ($receiver_list as $receiver) {
839 if ($receiver == self::PUBLIC_COLLECTION) {
840 $receiver = ActivityPub::PUBLIC_COLLECTION;
842 $urls[$element][] = $receiver;
850 * Fetch the receiver list from an activity array
852 * @param array $activity
853 * @param string $actor
855 * @param boolean $fetch_unlisted
857 * @return array with receivers (user id)
860 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
862 $reply = $receivers = [];
864 // When it is an answer, we inherite the receivers from the parent
865 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
866 if (!empty($replyto)) {
869 // Fix possibly wrong item URI (could be an answer to a plink uri)
870 $fixedReplyTo = Item::getURIByLink($replyto);
871 if (!empty($fixedReplyTo)) {
872 $reply[] = $fixedReplyTo;
876 // Fetch all posts that refer to the object id
877 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
878 if (!empty($object_id)) {
879 $reply[] = $object_id;
882 if (!empty($reply)) {
883 $parents = Post::select(['uid'], ['uri' => $reply]);
884 while ($parent = Post::fetch($parents)) {
885 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
887 DBA::close($parents);
890 if (!empty($actor)) {
891 $profile = APContact::getByURL($actor);
892 $followers = $profile['followers'] ?? '';
893 $is_forum = ($actor['type'] ?? '') == 'Group';
894 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
896 Logger::info('Empty actor', ['activity' => $activity]);
901 // We have to prevent false follower assumptions upon thread completions
902 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
904 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
905 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
906 if (empty($receiver_list)) {
910 foreach ($receiver_list as $receiver) {
911 if ($receiver == self::PUBLIC_COLLECTION) {
912 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
915 // Add receiver "-1" for unlisted posts
916 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
917 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
920 // Fetch the receivers for the public and the followers collection
921 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
922 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
926 // Fetching all directly addressed receivers
927 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
928 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
929 if (!DBA::isResult($contact)) {
933 // Check if the potential receiver is following the actor
934 // Exception: The receiver is targetted via "to" or this is a comment
935 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
936 $networks = Protocol::FEDERATED;
937 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
938 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
940 // Forum posts are only accepted from forum contacts
941 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
942 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
945 if (!DBA::exists('contact', $condition)) {
950 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
951 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
954 $type = self::TARGET_TO;
957 $type = self::TARGET_CC;
960 $type = self::TARGET_BTO;
963 $type = self::TARGET_BCC;
967 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
972 self::switchContacts($receivers, $actor);
978 * Fetch the receiver list of a given actor
980 * @param string $actor
982 * @param array $receivers
983 * @param integer $target_type
985 * @return array with receivers (user id)
988 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
990 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
991 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
993 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
994 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
995 while ($contact = DBA::fetch($contacts)) {
996 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
997 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1000 DBA::close($contacts);
1002 // The queries are split because of performance issues
1003 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1004 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1005 while ($contact = DBA::fetch($contacts)) {
1006 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1007 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1010 DBA::close($contacts);
1015 * Tests if the contact is a valid receiver for this actor
1017 * @param array $contact
1018 * @param string $actor
1019 * @param array $tags
1021 * @return bool with receivers (user id)
1022 * @throws \Exception
1024 private static function isValidReceiverForActor($contact, $tags)
1026 // Are we following the contact? Then this is a valid receiver
1027 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1031 // When the possible receiver isn't a community, then it is no valid receiver
1032 $owner = User::getOwnerDataById($contact['uid']);
1033 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1037 // Is the community account tagged?
1038 foreach ($tags as $tag) {
1039 if ($tag['type'] != 'Mention') {
1043 if (Strings::compareLink($tag['href'], $owner['url'])) {
1052 * Switches existing contacts to ActivityPub
1054 * @param integer $cid Contact ID
1055 * @param integer $uid User ID
1056 * @param string $url Profile URL
1057 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1058 * @throws \ImagickException
1060 public static function switchContact($cid, $uid, $url)
1062 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1063 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1067 if (Contact::updateFromProbe($cid)) {
1068 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1071 // Send a new follow request to be sure that the connection still exists
1072 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1073 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1074 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1083 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1084 * @throws \ImagickException
1086 private static function switchContacts($receivers, $actor)
1088 if (empty($actor)) {
1092 foreach ($receivers as $receiver) {
1093 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1094 if (DBA::isResult($contact)) {
1095 self::switchContact($contact['id'], $receiver['uid'], $actor);
1098 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1099 if (DBA::isResult($contact)) {
1100 self::switchContact($contact['id'], $receiver['uid'], $actor);
1108 * @param $object_data
1109 * @param array $activity
1113 private static function addActivityFields($object_data, $activity)
1115 if (!empty($activity['published']) && empty($object_data['published'])) {
1116 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1119 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1120 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1123 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1124 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1126 if (!empty($object_data['object_id'])) {
1127 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1128 $objectId = Item::getURIByLink($object_data['object_id']);
1129 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1130 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1131 $object_data['object_id'] = $objectId;
1135 return $object_data;
1139 * Fetches the object data from external ressources if needed
1141 * @param string $object_id Object ID of the the provided object
1142 * @param array $object The provided object array
1143 * @param boolean $trust_source Do we trust the provided object?
1144 * @param integer $uid User ID for the signature that we use to fetch data
1146 * @return array|false with trusted and valid object data
1147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1148 * @throws \ImagickException
1150 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1152 // By fetching the type we check if the object is complete.
1153 $type = JsonLD::fetchElement($object, '@type');
1155 if (!$trust_source || empty($type)) {
1156 $data = ActivityPub::fetchContent($object_id, $uid);
1157 if (!empty($data)) {
1158 $object = JsonLD::compact($data);
1159 Logger::info('Fetched content for ' . $object_id);
1161 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1163 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1164 if (!DBA::isResult($item)) {
1165 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1168 Logger::info('Using already stored item for url ' . $object_id);
1169 $data = ActivityPub\Transmitter::createNote($item);
1170 $object = JsonLD::compact($data);
1173 $id = JsonLD::fetchElement($object, '@id');
1175 Logger::info('Empty id');
1179 if ($id != $object_id) {
1180 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1184 Logger::info('Using original object for url ' . $object_id);
1187 $type = JsonLD::fetchElement($object, '@type');
1189 Logger::info('Empty type');
1193 // Lemmy is resharing "create" activities instead of content
1194 // We fetch the content from the activity.
1195 if (in_array($type, ['as:Create'])) {
1196 $object = $object['as:object'];
1197 $type = JsonLD::fetchElement($object, '@type');
1199 Logger::info('Empty type');
1202 $object_data = self::processObject($object);
1205 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1206 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1207 $object_data = self::processObject($object);
1209 if (!empty($data)) {
1210 $object_data['raw'] = json_encode($data);
1212 return $object_data;
1215 if ($type == 'as:Announce') {
1216 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1217 if (empty($object_id) || !is_string($object_id)) {
1220 return self::fetchObject($object_id, [], false, $uid);
1223 Logger::info('Unhandled object type: ' . $type);
1228 * Converts the language element (Used by Peertube)
1230 * @param array $languages
1231 * @return array Languages
1233 public static function processLanguages(array $languages)
1235 if (empty($languages)) {
1239 $language_list = [];
1241 foreach ($languages as $language) {
1242 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1243 $language_list[$language['_:identifier']] = $language['as:name'];
1246 return $language_list;
1250 * Convert tags from JSON-LD format into a simplified format
1252 * @param array $tags Tags in JSON-LD format
1254 * @return array with tags in a simplified format
1256 public static function processTags(array $tags)
1260 foreach ($tags as $tag) {
1265 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1266 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1267 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1269 if (empty($element['type'])) {
1273 if (empty($element['href'])) {
1274 $element['href'] = $element['name'];
1277 $taglist[] = $element;
1283 * Convert emojis from JSON-LD format into a simplified format
1285 * @param array $emojis
1286 * @return array with emojis in a simplified format
1288 private static function processEmojis(array $emojis)
1292 foreach ($emojis as $emoji) {
1293 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1297 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1298 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1301 $emojilist[] = $element;
1308 * Convert attachments from JSON-LD format into a simplified format
1310 * @param array $attachments Attachments in JSON-LD format
1312 * @return array Attachments in a simplified format
1314 private static function processAttachments(array $attachments)
1318 // Removes empty values
1319 $attachments = array_filter($attachments);
1321 foreach ($attachments as $attachment) {
1322 switch (JsonLD::fetchElement($attachment, '@type')) {
1327 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1328 foreach ($urls as $url) {
1329 // Single scalar URL case
1330 if (is_string($url)) {
1335 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1336 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1337 if (Strings::startsWith($mediaType, 'image')) {
1346 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1347 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1349 'image' => $pageImage,
1353 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1354 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1355 $imagePreviewUrl = null;
1357 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1358 $imageVariants = [];
1359 $previewVariants = [];
1360 foreach ($urls as $url) {
1361 // Scalar URL, no discrimination possible
1362 if (is_string($url)) {
1363 $imageFullUrl = $url;
1367 // Not sure what to do with a different Link media type than the base Image, we skip
1368 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1372 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1374 // Default URL choice if no discriminating width is provided
1375 $imageFullUrl = $href ?? $imageFullUrl;
1377 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1379 if ($href && $width) {
1380 $imageVariants[$width] = $href;
1381 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1382 $previewVariants[abs(632 - $width)] = $href;
1386 if ($imageVariants) {
1387 // Taking the maximum size image
1388 ksort($imageVariants);
1389 $imageFullUrl = array_pop($imageVariants);
1391 // Taking the minimum number distance to the target distance
1392 ksort($previewVariants);
1393 $imagePreviewUrl = array_shift($previewVariants);
1396 unset($imageVariants);
1397 unset($previewVariants);
1401 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1402 'mediaType' => $mediaType,
1403 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1404 'url' => $imageFullUrl,
1405 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1410 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1411 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1412 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1413 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1414 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1415 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1416 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1425 * Fetch the original source or content with the "language" Markdown or HTML
1427 * @param array $object
1428 * @param array $object_data
1431 * @throws \Exception
1433 private static function getSource($object, $object_data)
1435 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1436 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1437 if (!empty($object_data['source'])) {
1438 return $object_data;
1441 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1442 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1443 if (!empty($object_data['source'])) {
1444 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1445 return $object_data;
1448 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1449 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1450 if (!empty($object_data['source'])) {
1451 $object_data['source'] = HTML::toBBCode($object_data['source']);
1452 return $object_data;
1455 return $object_data;
1459 * Extracts a potential alternate URL from a list of additional URL elements
1461 * @param array $urls
1464 private static function extractAlternateUrl(array $urls): string
1467 foreach ($urls as $key => $url) {
1468 // Not a list but a single URL element
1469 if (!is_numeric($key)) {
1473 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1477 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1482 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1483 if (empty($mediatype)) {
1487 if ($mediatype == 'text/html') {
1488 $alternateUrl = $href;
1492 return $alternateUrl;
1496 * Check if the "as:url" element is an array with multiple links
1497 * This is the case with audio and video posts.
1498 * Then the links are added as attachments
1500 * @param array $urls The object URL list
1501 * @return array an array of attachments
1503 private static function processAttachmentUrls(array $urls): array
1506 foreach ($urls as $key => $url) {
1507 // Not a list but a single URL element
1508 if (!is_numeric($key)) {
1512 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1516 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1521 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1522 if (empty($mediatype)) {
1526 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1528 if ($filetype == 'audio') {
1529 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1530 } elseif ($filetype == 'video') {
1531 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1532 // PeerTube audio-only track
1533 if ($height === 0) {
1537 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1538 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1539 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1540 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1542 // For Torrent links we always store the highest resolution
1543 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1547 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1548 } elseif ($mediatype == 'application/x-mpegURL') {
1549 // PeerTube exception, actual video link is in the tags of this URL element
1550 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1554 return array_values($attachments);
1558 * Fetches data from the object part of an activity
1560 * @param array $object
1563 * @throws \Exception
1565 private static function processObject($object)
1567 if (!JsonLD::fetchElement($object, '@id')) {
1572 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1573 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1574 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1576 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1577 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1578 $object_data['reply-to-id'] = $object_data['id'];
1580 // On activities the "reply to" is the id of the object it refers to
1581 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1582 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1583 if (!empty($object_id)) {
1584 $object_data['reply-to-id'] = $object_id;
1588 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1589 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1590 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1591 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1592 $object_data['reply-to-id'] = $replyToId;
1596 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1597 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1599 if (empty($object_data['updated'])) {
1600 $object_data['updated'] = $object_data['published'];
1603 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1604 $object_data['published'] = $object_data['updated'];
1607 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1608 if (empty($actor)) {
1609 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1612 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1613 $location = JsonLD::fetchElement($location, 'location', '@value');
1615 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1616 // down to HTML and then finally format to plaintext.
1617 $location = Markdown::convert($location);
1618 $location = BBCode::toPlaintext($location);
1621 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1622 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1623 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1624 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1625 $object_data['actor'] = $object_data['author'] = $actor;
1626 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1627 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1628 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1629 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1630 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1631 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1632 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1633 $object_data = self::getSource($object, $object_data);
1634 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1635 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1636 $object_data['location'] = $location;
1637 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1638 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1639 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1640 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1641 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1642 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1643 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1644 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1645 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1646 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1647 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1649 // Special treatment for Hubzilla links
1650 if (is_array($object_data['alternate-url'])) {
1651 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1653 if (!is_string($object_data['alternate-url'])) {
1654 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1658 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1659 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1660 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1663 // For page types we expect that the alternate url posts to some page.
1664 // So we add this to the attachments if it differs from the id.
1665 // Currently only Lemmy is using the page type.
1666 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1667 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1668 $object_data['alternate-url'] = null;
1671 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1672 $receivers = $reception_types = [];
1673 foreach ($receiverdata as $key => $data) {
1674 $receivers[$key] = $data['uid'];
1675 $reception_types[$data['uid']] = $data['type'] ?? 0;
1678 $object_data['receiver_urls'] = self::getReceiverURL($object);
1679 $object_data['receiver'] = $receivers;
1680 $object_data['reception_type'] = $reception_types;
1682 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1683 unset($object_data['receiver'][-1]);
1684 unset($object_data['reception_type'][-1]);
1686 // Common object data:
1689 // @context, type, actor, signature, mediaType, duration, replies, icon
1691 // Also missing: (Defined in the standard, but currently unused)
1692 // audience, preview, endTime, startTime, image
1697 // contentMap, announcement_count, announcements, context_id, likes, like_count
1698 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1703 // category, licence, language, commentsEnabled
1706 // views, waitTranscoding, state, support, subtitleLanguage
1707 // likes, dislikes, shares, comments
1709 return $object_data;