]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Merge pull request #11150 from annando/user-banner
[friendica.git] / src / Protocol / ActivityPub / Receiver.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
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\Model\Contact;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Item;
33 use Friendica\Model\Post;
34 use Friendica\Model\User;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Util\HTTPSignature;
38 use Friendica\Util\JsonLD;
39 use Friendica\Util\LDSignature;
40 use Friendica\Util\Strings;
41
42 /**
43  * ActivityPub Receiver Protocol class
44  *
45  * To-Do:
46  * @todo Undo Announce
47  *
48  * Check what this is meant to do:
49  * - Add
50  * - Block
51  * - Flag
52  * - Remove
53  * - Undo Block
54  */
55 class Receiver
56 {
57         const PUBLIC_COLLECTION = 'as:Public';
58         const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
59         const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
60         const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
61
62         const TARGET_UNKNOWN = 0;
63         const TARGET_TO = 1;
64         const TARGET_CC = 2;
65         const TARGET_BTO = 3;
66         const TARGET_BCC = 4;
67         const TARGET_FOLLOWER = 5;
68         const TARGET_ANSWER = 6;
69         const TARGET_GLOBAL = 7;
70
71         /**
72          * Checks incoming message from the inbox
73          *
74          * @param         $body
75          * @param         $header
76          * @param integer $uid User ID
77          * @throws \Exception
78          */
79         public static function processInbox($body, $header, $uid)
80         {
81                 $activity = json_decode($body, true);
82                 if (empty($activity)) {
83                         Logger::warning('Invalid body.');
84                         return;
85                 }
86
87                 $ldactivity = JsonLD::compact($activity);
88
89                 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
90
91                 $apcontact = APContact::getByURL($actor);
92                 if (empty($apcontact)) {
93                         Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
94                         return;
95                 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
96                         self::processRelayPost($ldactivity, $actor);
97                         return;
98                 } else {
99                         APContact::unmarkForArchival($apcontact);
100                 }
101
102                 $http_signer = HTTPSignature::getSigner($body, $header);
103                 if ($http_signer === false) {
104                         Logger::warning('Invalid HTTP signature, message will be discarded.');
105                         return;
106                 } elseif (empty($http_signer)) {
107                         Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
108                         return;
109                 } else {
110                         Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
111                 }
112
113                 $signer = [$http_signer];
114
115                 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
116
117                 if (LDSignature::isSigned($activity)) {
118                         $ld_signer = LDSignature::getSigner($activity);
119                         if (empty($ld_signer)) {
120                                 Logger::info('Invalid JSON-LD signature from ' . $actor);
121                         } elseif ($ld_signer != $http_signer) {
122                                 $signer[] = $ld_signer;
123                         }
124                         if (!empty($ld_signer && ($actor == $http_signer))) {
125                                 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
126                                 $trust_source = true;
127                         } elseif (!empty($ld_signer)) {
128                                 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
129                                 $trust_source = true;
130                         } elseif ($actor == $http_signer) {
131                                 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
132                                 $trust_source = true;
133                         } else {
134                                 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
135                                 $trust_source = false;
136                         }
137                 } elseif ($actor == $http_signer) {
138                         Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
139                         $trust_source = true;
140                 } else {
141                         Logger::info('No JSON-LD signature, different actor.');
142                         $trust_source = false;
143                 }
144
145                 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
146         }
147
148         /**
149          * Process incoming posts from relays
150          *
151          * @param array  $activity
152          * @param string $actor
153          * @return void
154          */
155         private static function processRelayPost(array $activity, string $actor)
156         {
157                 $type = JsonLD::fetchElement($activity, '@type');
158                 if (!$type) {
159                         Logger::info('Empty type', ['activity' => $activity]);
160                         return;
161                 }
162
163                 if ($type != 'as:Announce') {
164                         Logger::info('Not an announcement', ['activity' => $activity]);
165                         return;
166                 }
167
168                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
169                 if (empty($object_id)) {
170                         Logger::info('No object id found', ['activity' => $activity]);
171                         return;
172                 }
173
174                 $contact = Contact::getByURL($actor);
175                 if (empty($contact)) {
176                         Logger::info('Relay contact not found', ['actor' => $actor]);
177                         return;
178                 }
179
180                 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
181                         Logger::notice('Relay is no sharer', ['actor' => $actor]);
182                         return;
183                 }
184
185                 Logger::info('Got relayed message id', ['id' => $object_id]);
186
187                 $item_id = Item::searchByLink($object_id);
188                 if ($item_id) {
189                         Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
190                         return;
191                 }
192
193                 $id = Processor::fetchMissingActivity($object_id, [], $actor);
194                 if (empty($id)) {
195                         Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
196                         return;
197                 }
198
199                 $item_id = Item::searchByLink($object_id);
200                 if ($item_id) {
201                         Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
202                 } else {
203                         Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
204                 }
205         }
206
207         /**
208          * Fetches the object type for a given object id
209          *
210          * @param array   $activity
211          * @param string  $object_id Object ID of the the provided object
212          * @param integer $uid       User ID
213          *
214          * @return string with object type
215          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216          * @throws \ImagickException
217          */
218         private static function fetchObjectType($activity, $object_id, $uid = 0)
219         {
220                 if (!empty($activity['as:object'])) {
221                         $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
222                         if (!empty($object_type)) {
223                                 return $object_type;
224                         }
225                 }
226
227                 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
228                         // We just assume "note" since it doesn't make a difference for the further processing
229                         return 'as:Note';
230                 }
231
232                 $profile = APContact::getByURL($object_id);
233                 if (!empty($profile['type'])) {
234                         APContact::unmarkForArchival($profile);
235                         return 'as:' . $profile['type'];
236                 }
237
238                 $data = ActivityPub::fetchContent($object_id, $uid);
239                 if (!empty($data)) {
240                         $object = JsonLD::compact($data);
241                         $type = JsonLD::fetchElement($object, '@type');
242                         if (!empty($type)) {
243                                 return $type;
244                         }
245                 }
246
247                 return null;
248         }
249
250         /**
251          * Prepare the object array
252          *
253          * @param array   $activity     Array with activity data
254          * @param integer $uid          User ID
255          * @param boolean $push         Message had been pushed to our system
256          * @param boolean $trust_source Do we trust the source?
257          *
258          * @return array with object data
259          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
260          * @throws \ImagickException
261          */
262         public static function prepareObjectData($activity, $uid, $push, &$trust_source)
263         {
264                 $id = JsonLD::fetchElement($activity, '@id');
265                 if (!empty($id) && !$trust_source) {
266                         $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
267                         if (!empty($fetched_activity)) {
268                                 $object = JsonLD::compact($fetched_activity);
269                                 $fetched_id = JsonLD::fetchElement($object, '@id');
270                                 if ($fetched_id == $id) {
271                                         Logger::info('Activity had been fetched successfully', ['id' => $id]);
272                                         $trust_source = true;
273                                         $activity = $object;
274                                 } else {
275                                         Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
276                                 }
277                         } else {
278                                 Logger::info('Activity could not been fetched', ['id' => $id]);
279                         }
280                 }
281
282                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
283                 if (empty($actor)) {
284                         Logger::info('Empty actor', ['activity' => $activity]);
285                         return [];
286                 }
287
288                 $type = JsonLD::fetchElement($activity, '@type');
289
290                 // Fetch all receivers from to, cc, bto and bcc
291                 $receiverdata = self::getReceivers($activity, $actor);
292                 $receivers = $reception_types = [];
293                 foreach ($receiverdata as $key => $data) {
294                         $receivers[$key] = $data['uid'];
295                         $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
296                 }
297
298                 // When it is a delivery to a personal inbox we add that user to the receivers
299                 if (!empty($uid)) {
300                         $additional = [$uid => $uid];
301                         $receivers = array_replace($receivers, $additional);
302                         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]))) {
303                                 $reception_types[$uid] = self::TARGET_BCC;
304                         }
305                 } else {
306                         // We possibly need some user to fetch private content,
307                         // so we fetch the first out ot the list.
308                         $uid = self::getFirstUserFromReceivers($receivers);
309                 }
310
311                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
312                 if (empty($object_id)) {
313                         Logger::info('No object found');
314                         return [];
315                 }
316
317                 if (!is_string($object_id)) {
318                         Logger::info('Invalid object id', ['object' => $object_id]);
319                         return [];
320                 }
321
322                 $object_type = self::fetchObjectType($activity, $object_id, $uid);
323
324                 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
325                 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
326                         $data = ActivityPub::fetchContent($object_id, $uid);
327                         if (!empty($data)) {
328                                 $type = $object_type;
329                                 $activity = JsonLD::compact($data);
330
331                                 // Some variables need to be refetched since the activity changed
332                                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
333                                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
334                                 $object_type = self::fetchObjectType($activity, $object_id, $uid);
335                         }
336                 }
337
338                 // Any activities on account types must not be altered
339                 if (in_array($object_type, self::ACCOUNT_TYPES)) {
340                         $object_data = [];
341                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
342                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
343                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
344                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
345                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
346                         $object_data['push'] = $push;
347                 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce']) || strpos($type, '#emojiReaction')) {
348                 // Fetch the content only on activities where this matters
349                 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
350                         // Always fetch on "Announce"
351                         $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
352                         if (empty($object_data)) {
353                                 Logger::info("Object data couldn't be processed");
354                                 return [];
355                         }
356
357                         $object_data['object_id'] = $object_id;
358
359                         if ($type == 'as:Announce') {
360                                 $object_data['push'] = false;
361                         } else {
362                                 $object_data['push'] = $push;
363                         }
364
365                         // Test if it is an answer to a mail
366                         if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
367                                 $object_data['directmessage'] = true;
368                         } else {
369                                 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
370                         }
371                 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
372                         // Create a mostly empty array out of the activity data (instead of the object).
373                         // This way we later don't have to check for the existence of each individual array element.
374                         $object_data = self::processObject($activity);
375                         $object_data['name'] = $type;
376                         $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
377                         $object_data['object_id'] = $object_id;
378                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
379                         $object_data['push'] = $push;
380                 } elseif (in_array($type, ['as:Add'])) {
381                         $object_data = [];
382                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
383                         $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
384                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
385                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
386                         $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
387                         $object_data['push'] = $push;
388                 } else {
389                         $object_data = [];
390                         $object_data['id'] = JsonLD::fetchElement($activity, '@id');
391                         $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
392                         $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
393                         $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
394                         $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
395                         $object_data['push'] = $push;
396
397                         // An Undo is done on the object of an object, so we need that type as well
398                         if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
399                                 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
400                         }
401                 }
402
403                 $object_data = self::addActivityFields($object_data, $activity);
404
405                 if (empty($object_data['object_type'])) {
406                         $object_data['object_type'] = $object_type;
407                 }
408
409                 $object_data['type'] = $type;
410                 $object_data['actor'] = $actor;
411                 $object_data['item_receiver'] = $receivers;
412                 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
413                 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
414
415                 $author = $object_data['author'] ?? $actor;
416                 if (!empty($author) && !empty($object_data['id'])) {
417                         $author_host = parse_url($author, PHP_URL_HOST);
418                         $id_host = parse_url($object_data['id'], PHP_URL_HOST);
419                         if ($author_host == $id_host) {
420                                 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
421                         } else {
422                                 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
423                                 $trust_source = false;
424                         }
425                 }
426
427                 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
428
429                 return $object_data;
430         }
431
432         /**
433          * Fetches the first user id from the receiver array
434          *
435          * @param array $receivers Array with receivers
436          * @return integer user id;
437          */
438         public static function getFirstUserFromReceivers($receivers)
439         {
440                 foreach ($receivers as $receiver) {
441                         if (!empty($receiver)) {
442                                 return $receiver;
443                         }
444                 }
445                 return 0;
446         }
447
448         /**
449          * Processes the activity object
450          *
451          * @param array   $activity     Array with activity data
452          * @param string  $body
453          * @param integer $uid          User ID
454          * @param boolean $trust_source Do we trust the source?
455          * @param boolean $push         Message had been pushed to our system
456          * @throws \Exception
457          */
458         public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
459         {
460                 $type = JsonLD::fetchElement($activity, '@type');
461                 if (!$type) {
462                         Logger::info('Empty type', ['activity' => $activity]);
463                         return;
464                 }
465
466                 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
467                         Logger::info('Empty object', ['activity' => $activity]);
468                         return;
469                 }
470
471                 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
472                 if (empty($actor)) {
473                         Logger::info('Empty actor', ['activity' => $activity]);
474                         return;
475                 }
476
477                 if (is_array($activity['as:object'])) {
478                         $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
479                 } else {
480                         $attributed_to = '';
481                 }
482
483                 // Test the provided signatures against the actor and "attributedTo"
484                 if ($trust_source) {
485                         if (!empty($attributed_to) && !empty($actor)) {
486                                 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
487                         } else {
488                                 $trust_source = in_array($actor, $signer);
489                         }
490                 }
491
492                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
493                 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
494                 if (empty($object_data)) {
495                         Logger::info('No object data found', ['activity' => $activity]);
496                         return;
497                 }
498
499                 // Lemmy is announcing activities.
500                 // We are changing the announces into regular activities.
501                 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
502                         $type = $object_data['type'];
503                 }
504
505                 if (!$trust_source) {
506                         Logger::info('Activity trust could not be achieved.',  ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
507                         return;
508                 }
509
510                 if (!empty($body) && empty($object_data['raw'])) {
511                         $object_data['raw'] = $body;
512                 }
513
514                 // Internal flag for thread completion. See Processor.php
515                 if (!empty($activity['thread-completion'])) {
516                         $object_data['thread-completion'] = $activity['thread-completion'];
517                 }
518
519                 // Internal flag for posts that arrived via relay
520                 if (!empty($activity['from-relay'])) {
521                         $object_data['from-relay'] = $activity['from-relay'];
522                 }
523
524                 switch ($type) {
525                         case 'as:Create':
526                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
527                                         $item = ActivityPub\Processor::createItem($object_data);
528                                         ActivityPub\Processor::postItem($object_data, $item);
529                                 }
530                                 break;
531
532                         case 'as:Add':
533                                 if ($object_data['object_type'] == 'as:tag') {
534                                         ActivityPub\Processor::addTag($object_data);
535                                 }
536                                 break;
537
538                         case 'as:Announce':
539                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
540                                         $object_data['thread-completion'] = Contact::getIdForURL($actor);
541
542                                         $item = ActivityPub\Processor::createItem($object_data);
543                                         if (empty($item)) {
544                                                 return;
545                                         }
546
547                                         $item['post-reason'] = Item::PR_ANNOUNCEMENT;
548                                         ActivityPub\Processor::postItem($object_data, $item);
549
550                                         $announce_object_data = self::processObject($activity);
551                                         $announce_object_data['name'] = $type;
552                                         $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
553                                         $announce_object_data['object_id'] = $object_data['object_id'];
554                                         $announce_object_data['object_type'] = $object_data['object_type'];
555                                         $announce_object_data['push'] = $push;
556
557                                         if (!empty($body)) {
558                                                 $announce_object_data['raw'] = $body;
559                                         }
560
561                                         ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
562                                 }
563                                 break;
564
565                         case 'as:Like':
566                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
567                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
568                                 }
569                                 break;
570
571                         case 'as:Dislike':
572                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
573                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
574                                 }
575                                 break;
576
577                         case 'as:TentativeAccept':
578                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
579                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
580                                 }
581                                 break;
582
583                         case 'as:Update':
584                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
585                                         ActivityPub\Processor::updateItem($object_data);
586                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
587                                         ActivityPub\Processor::updatePerson($object_data);
588                                 }
589                                 break;
590
591                         case 'as:Delete':
592                                 if ($object_data['object_type'] == 'as:Tombstone') {
593                                         ActivityPub\Processor::deleteItem($object_data);
594                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
595                                         ActivityPub\Processor::deletePerson($object_data);
596                                 }
597                                 break;
598
599                         case 'as:Follow':
600                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
601                                         ActivityPub\Processor::followUser($object_data);
602                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
603                                         $object_data['reply-to-id'] = $object_data['object_id'];
604                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
605                                 }
606                                 break;
607
608                         case 'as:Accept':
609                                 if ($object_data['object_type'] == 'as:Follow') {
610                                         ActivityPub\Processor::acceptFollowUser($object_data);
611                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
612                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
613                                 }
614                                 break;
615
616                         case 'as:Reject':
617                                 if ($object_data['object_type'] == 'as:Follow') {
618                                         ActivityPub\Processor::rejectFollowUser($object_data);
619                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
620                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
621                                 }
622                                 break;
623
624                         case 'as:Undo':
625                                 if (($object_data['object_type'] == 'as:Follow') &&
626                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
627                                         ActivityPub\Processor::undoFollowUser($object_data);
628                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
629                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
630                                         ActivityPub\Processor::rejectFollowUser($object_data);
631                                 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
632                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
633                                         ActivityPub\Processor::undoActivity($object_data);
634                                 }
635                                 break;
636
637                         default:
638                                 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
639                                 break;
640                 }
641         }
642
643         /**
644          * Fetch the receiver list from an activity array
645          *
646          * @param array   $activity
647          * @param string  $actor
648          * @param array   $tags
649          * @param boolean $fetch_unlisted
650          *
651          * @return array with receivers (user id)
652          * @throws \Exception
653          */
654         private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
655         {
656                 $reply = $receivers = [];
657
658                 // When it is an answer, we inherite the receivers from the parent
659                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
660                 if (!empty($replyto)) {
661                         $reply = [$replyto];
662
663                         // Fix possibly wrong item URI (could be an answer to a plink uri)
664                         $fixedReplyTo = Item::getURIByLink($replyto);
665                         if (!empty($fixedReplyTo)) {
666                                 $reply[] = $fixedReplyTo;
667                         }
668                 }
669
670                 // Fetch all posts that refer to the object id
671                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
672                 if (!empty($object_id)) {
673                         $reply[] = $object_id;
674                 }
675
676                 if (!empty($reply)) {
677                         $parents = Post::select(['uid'], ['uri' => $reply]);
678                         while ($parent = Post::fetch($parents)) {
679                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
680                         }
681                         DBA::close($parents);
682                 }
683
684                 if (!empty($actor)) {
685                         $profile   = APContact::getByURL($actor);
686                         $followers = $profile['followers'] ?? '';
687                         $is_forum  = ($actor['type'] ?? '') == 'Group';
688                         Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
689                 } else {
690                         Logger::info('Empty actor', ['activity' => $activity]);
691                         $followers = '';
692                         $is_forum  = false;
693                 }
694
695                 // We have to prevent false follower assumptions upon thread completions
696                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
697
698                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
699                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
700                         if (empty($receiver_list)) {
701                                 continue;
702                         }
703
704                         foreach ($receiver_list as $receiver) {
705                                 if ($receiver == self::PUBLIC_COLLECTION) {
706                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
707                                 }
708
709                                 // Add receiver "-1" for unlisted posts
710                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
711                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
712                                 }
713
714                                 // Fetch the receivers for the public and the followers collection
715                                 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
716                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
717                                         continue;
718                                 }
719
720                                 // Fetching all directly addressed receivers
721                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
722                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
723                                 if (!DBA::isResult($contact)) {
724                                         continue;
725                                 }
726
727                                 // Check if the potential receiver is following the actor
728                                 // Exception: The receiver is targetted via "to" or this is a comment
729                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
730                                         $networks = Protocol::FEDERATED;
731                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
732                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
733
734                                         // Forum posts are only accepted from forum contacts
735                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
736                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
737                                         }
738
739                                         if (!DBA::exists('contact', $condition)) {
740                                                 continue;
741                                         }
742                                 }
743
744                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
745                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
746                                         switch ($element) {
747                                                 case 'as:to':
748                                                         $type = self::TARGET_TO;
749                                                         break;
750                                                 case 'as:cc':
751                                                         $type = self::TARGET_CC;
752                                                         break;
753                                                 case 'as:bto':
754                                                         $type = self::TARGET_BTO;
755                                                         break;
756                                                 case 'as:bcc':
757                                                         $type = self::TARGET_BCC;
758                                                         break;
759                                         }
760
761                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
762                                 }
763                         }
764                 }
765
766                 self::switchContacts($receivers, $actor);
767
768                 return $receivers;
769         }
770
771         /**
772          * Fetch the receiver list of a given actor
773          *
774          * @param string  $actor
775          * @param array   $tags
776          * @param array   $receivers
777          * @param integer $target_type
778          *
779          * @return array with receivers (user id)
780          * @throws \Exception
781          */
782         private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
783         {
784                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
785                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
786
787                 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
788                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
789                 while ($contact = DBA::fetch($contacts)) {
790                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
791                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
792                         }
793                 }
794                 DBA::close($contacts);
795
796                 // The queries are split because of performance issues
797                 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
798                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
799                 while ($contact = DBA::fetch($contacts)) {
800                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
801                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
802                         }
803                 }
804                 DBA::close($contacts);
805                 return $receivers;
806         }
807
808         /**
809          * Tests if the contact is a valid receiver for this actor
810          *
811          * @param array  $contact
812          * @param string $actor
813          * @param array  $tags
814          *
815          * @return bool with receivers (user id)
816          * @throws \Exception
817          */
818         private static function isValidReceiverForActor($contact, $tags)
819         {
820                 // Are we following the contact? Then this is a valid receiver
821                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
822                         return true;
823                 }
824
825                 // When the possible receiver isn't a community, then it is no valid receiver
826                 $owner = User::getOwnerDataById($contact['uid']);
827                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
828                         return false;
829                 }
830
831                 // Is the community account tagged?
832                 foreach ($tags as $tag) {
833                         if ($tag['type'] != 'Mention') {
834                                 continue;
835                         }
836
837                         if (Strings::compareLink($tag['href'], $owner['url'])) {
838                                 return true;
839                         }
840                 }
841
842                 return false;
843         }
844
845         /**
846          * Switches existing contacts to ActivityPub
847          *
848          * @param integer $cid Contact ID
849          * @param integer $uid User ID
850          * @param string  $url Profile URL
851          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
852          * @throws \ImagickException
853          */
854         public static function switchContact($cid, $uid, $url)
855         {
856                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
857                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
858                         return;
859                 }
860
861                 if (Contact::updateFromProbe($cid)) {
862                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
863                 }
864
865                 // Send a new follow request to be sure that the connection still exists
866                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
867                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
868                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
869                 }
870         }
871
872         /**
873          *
874          *
875          * @param $receivers
876          * @param $actor
877          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
878          * @throws \ImagickException
879          */
880         private static function switchContacts($receivers, $actor)
881         {
882                 if (empty($actor)) {
883                         return;
884                 }
885
886                 foreach ($receivers as $receiver) {
887                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
888                         if (DBA::isResult($contact)) {
889                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
890                         }
891
892                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
893                         if (DBA::isResult($contact)) {
894                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
895                         }
896                 }
897         }
898
899         /**
900          *
901          *
902          * @param       $object_data
903          * @param array $activity
904          *
905          * @return mixed
906          */
907         private static function addActivityFields($object_data, $activity)
908         {
909                 if (!empty($activity['published']) && empty($object_data['published'])) {
910                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
911                 }
912
913                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
914                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
915                 }
916
917                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
918                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
919
920                 if (!empty($object_data['object_id'])) {
921                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
922                         $objectId = Item::getURIByLink($object_data['object_id']);
923                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
924                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
925                                 $object_data['object_id'] = $objectId;
926                         }
927                 }
928
929                 return $object_data;
930         }
931
932         /**
933          * Fetches the object data from external ressources if needed
934          *
935          * @param string  $object_id    Object ID of the the provided object
936          * @param array   $object       The provided object array
937          * @param boolean $trust_source Do we trust the provided object?
938          * @param integer $uid          User ID for the signature that we use to fetch data
939          *
940          * @return array|false with trusted and valid object data
941          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
942          * @throws \ImagickException
943          */
944         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
945         {
946                 // By fetching the type we check if the object is complete.
947                 $type = JsonLD::fetchElement($object, '@type');
948
949                 if (!$trust_source || empty($type)) {
950                         $data = ActivityPub::fetchContent($object_id, $uid);
951                         if (!empty($data)) {
952                                 $object = JsonLD::compact($data);
953                                 Logger::info('Fetched content for ' . $object_id);
954                         } else {
955                                 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
956
957                                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
958                                 if (!DBA::isResult($item)) {
959                                         Logger::info('Object with url ' . $object_id . ' was not found locally.');
960                                         return false;
961                                 }
962                                 Logger::info('Using already stored item for url ' . $object_id);
963                                 $data = ActivityPub\Transmitter::createNote($item);
964                                 $object = JsonLD::compact($data);
965                         }
966
967                         $id = JsonLD::fetchElement($object, '@id');
968                         if (empty($id)) {
969                                 Logger::info('Empty id');
970                                 return false;
971                         }
972
973                         if ($id != $object_id) {
974                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
975                                 return false;
976                         }
977                 } else {
978                         Logger::info('Using original object for url ' . $object_id);
979                 }
980
981                 $type = JsonLD::fetchElement($object, '@type');
982                 if (empty($type)) {
983                         Logger::info('Empty type');
984                         return false;
985                 }
986
987                 // Lemmy is resharing "create" activities instead of content
988                 // We fetch the content from the activity.
989                 if (in_array($type, ['as:Create'])) {
990                         $object = $object['as:object'];
991                         $type = JsonLD::fetchElement($object, '@type');
992                         if (empty($type)) {
993                                 Logger::info('Empty type');
994                                 return false;
995                         }
996                         $object_data = self::processObject($object);
997                 }
998
999                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1000                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1001                         $object_data = self::processObject($object);
1002
1003                         if (!empty($data)) {
1004                                 $object_data['raw'] = json_encode($data);
1005                         }
1006                         return $object_data;
1007                 }
1008
1009                 if ($type == 'as:Announce') {
1010                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
1011                         if (empty($object_id) || !is_string($object_id)) {
1012                                 return false;
1013                         }
1014                         return self::fetchObject($object_id, [], false, $uid);
1015                 }
1016
1017                 Logger::info('Unhandled object type: ' . $type);
1018                 return false;
1019         }
1020
1021         /**
1022          * Converts the language element (Used by Peertube)
1023          *
1024          * @param array $languages
1025          * @return array Languages
1026          */
1027         public static function processLanguages(array $languages)
1028         {
1029                 if (empty($languages)) {
1030                         return [];
1031                 }
1032
1033                 $language_list = [];
1034
1035                 foreach ($languages as $language) {
1036                         if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1037                                 $language_list[$language['_:identifier']] = $language['as:name'];
1038                         }
1039                 }
1040                 return $language_list;
1041         }
1042
1043         /**
1044          * Convert tags from JSON-LD format into a simplified format
1045          *
1046          * @param array $tags Tags in JSON-LD format
1047          *
1048          * @return array with tags in a simplified format
1049          */
1050         public static function processTags(array $tags)
1051         {
1052                 $taglist = [];
1053
1054                 foreach ($tags as $tag) {
1055                         if (empty($tag)) {
1056                                 continue;
1057                         }
1058
1059                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1060                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1061                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1062
1063                         if (empty($element['type'])) {
1064                                 continue;
1065                         }
1066
1067                         if (empty($element['href'])) {
1068                                 $element['href'] = $element['name'];
1069                         }
1070
1071                         $taglist[] = $element;
1072                 }
1073                 return $taglist;
1074         }
1075
1076         /**
1077          * Convert emojis from JSON-LD format into a simplified format
1078          *
1079          * @param array $emojis
1080          * @return array with emojis in a simplified format
1081          */
1082         private static function processEmojis(array $emojis)
1083         {
1084                 $emojilist = [];
1085
1086                 foreach ($emojis as $emoji) {
1087                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1088                                 continue;
1089                         }
1090
1091                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1092                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1093                                 'href' => $url];
1094
1095                         $emojilist[] = $element;
1096                 }
1097
1098                 return $emojilist;
1099         }
1100
1101         /**
1102          * Convert attachments from JSON-LD format into a simplified format
1103          *
1104          * @param array $attachments Attachments in JSON-LD format
1105          *
1106          * @return array Attachments in a simplified format
1107          */
1108         private static function processAttachments(array $attachments)
1109         {
1110                 $attachlist = [];
1111
1112                 // Removes empty values
1113                 $attachments = array_filter($attachments);
1114
1115                 foreach ($attachments as $attachment) {
1116                         switch (JsonLD::fetchElement($attachment, '@type')) {
1117                                 case 'as:Page':
1118                                         $pageUrl = null;
1119                                         $pageImage = null;
1120
1121                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1122                                         foreach ($urls as $url) {
1123                                                 // Single scalar URL case
1124                                                 if (is_string($url)) {
1125                                                         $pageUrl = $url;
1126                                                         continue;
1127                                                 }
1128
1129                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1130                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1131                                                 if (Strings::startsWith($mediaType, 'image')) {
1132                                                         $pageImage = $href;
1133                                                 } else {
1134                                                         $pageUrl = $href;
1135                                                 }
1136                                         }
1137
1138                                         $attachlist[] = [
1139                                                 'type'  => 'link',
1140                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1141                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1142                                                 'url'   => $pageUrl,
1143                                                 'image' => $pageImage,
1144                                         ];
1145                                         break;
1146                                 case 'as:Image':
1147                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1148                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1149                                         $imagePreviewUrl = null;
1150                                         // Multiple URLs?
1151                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1152                                                 $imageVariants = [];
1153                                                 $previewVariants = [];
1154                                                 foreach ($urls as $url) {
1155                                                         // Scalar URL, no discrimination possible
1156                                                         if (is_string($url)) {
1157                                                                 $imageFullUrl = $url;
1158                                                                 continue;
1159                                                         }
1160
1161                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1162                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1163                                                                 continue;
1164                                                         }
1165
1166                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1167
1168                                                         // Default URL choice if no discriminating width is provided
1169                                                         $imageFullUrl = $href ?? $imageFullUrl;
1170
1171                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1172
1173                                                         if ($href && $width) {
1174                                                                 $imageVariants[$width] = $href;
1175                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1176                                                                 $previewVariants[abs(632 - $width)] = $href;
1177                                                         }
1178                                                 }
1179
1180                                                 if ($imageVariants) {
1181                                                         // Taking the maximum size image
1182                                                         ksort($imageVariants);
1183                                                         $imageFullUrl = array_pop($imageVariants);
1184
1185                                                         // Taking the minimum number distance to the target distance
1186                                                         ksort($previewVariants);
1187                                                         $imagePreviewUrl = array_shift($previewVariants);
1188                                                 }
1189
1190                                                 unset($imageVariants);
1191                                                 unset($previewVariants);
1192                                         }
1193
1194                                         $attachlist[] = [
1195                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1196                                                 'mediaType' => $mediaType,
1197                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1198                                                 'url'   => $imageFullUrl,
1199                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1200                                         ];
1201                                         break;
1202                                 default:
1203                                         $attachlist[] = [
1204                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1205                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1206                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1207                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1208                                                 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1209                                                 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1210                                                 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1211                                         ];
1212                         }
1213                 }
1214
1215                 return $attachlist;
1216         }
1217
1218         /**
1219          * Fetch the original source or content with the "language" Markdown or HTML
1220          *
1221          * @param array $object
1222          * @param array $object_data
1223          *
1224          * @return array
1225          * @throws \Exception
1226          */
1227         private static function getSource($object, $object_data)
1228         {
1229                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1230                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1231                 if (!empty($object_data['source'])) {
1232                         return $object_data;
1233                 }
1234
1235                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1236                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1237                 if (!empty($object_data['source'])) {
1238                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1239                         return $object_data;
1240                 }
1241
1242                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1243                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1244                 if (!empty($object_data['source'])) {
1245                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1246                         return $object_data;
1247                 }
1248
1249                 return $object_data;
1250         }
1251
1252         /**
1253          * Extracts a potential alternate URL from a list of additional URL elements
1254          *
1255          * @param array $urls
1256          * @return string
1257          */
1258         private static function extractAlternateUrl(array $urls): string
1259         {
1260                 $alternateUrl = '';
1261                 foreach ($urls as $key => $url) {
1262                         // Not a list but a single URL element
1263                         if (!is_numeric($key)) {
1264                                 continue;
1265                         }
1266
1267                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1268                                 continue;
1269                         }
1270
1271                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1272                         if (empty($href)) {
1273                                 continue;
1274                         }
1275
1276                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1277                         if (empty($mediatype)) {
1278                                 continue;
1279                         }
1280
1281                         if ($mediatype == 'text/html') {
1282                                 $alternateUrl = $href;
1283                         }
1284                 }
1285
1286                 return $alternateUrl;
1287         }
1288
1289         /**
1290          * Check if the "as:url" element is an array with multiple links
1291          * This is the case with audio and video posts.
1292          * Then the links are added as attachments
1293          *
1294          * @param array $urls The object URL list
1295          * @return array an array of attachments
1296          */
1297         private static function processAttachmentUrls(array $urls): array
1298         {
1299                 $attachments = [];
1300                 foreach ($urls as $key => $url) {
1301                         // Not a list but a single URL element
1302                         if (!is_numeric($key)) {
1303                                 continue;
1304                         }
1305
1306                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1307                                 continue;
1308                         }
1309
1310                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1311                         if (empty($href)) {
1312                                 continue;
1313                         }
1314
1315                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1316                         if (empty($mediatype)) {
1317                                 continue;
1318                         }
1319
1320                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1321
1322                         if ($filetype == 'audio') {
1323                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1324                         } elseif ($filetype == 'video') {
1325                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1326                                 // PeerTube audio-only track
1327                                 if ($height === 0) {
1328                                         continue;
1329                                 }
1330
1331                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1332                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1333                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1334                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1335
1336                                 // For Torrent links we always store the highest resolution
1337                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1338                                         continue;
1339                                 }
1340
1341                                 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1342                         } elseif ($mediatype == 'application/x-mpegURL') {
1343                                 // PeerTube exception, actual video link is in the tags of this URL element
1344                                 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1345                         }
1346                 }
1347
1348                 return array_values($attachments);
1349         }
1350
1351         /**
1352          * Fetches data from the object part of an activity
1353          *
1354          * @param array $object
1355          *
1356          * @return array
1357          * @throws \Exception
1358          */
1359         private static function processObject($object)
1360         {
1361                 if (!JsonLD::fetchElement($object, '@id')) {
1362                         return false;
1363                 }
1364
1365                 $object_data = [];
1366                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1367                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1368                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1369
1370                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1371                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1372                         $object_data['reply-to-id'] = $object_data['id'];
1373
1374                         // On activities the "reply to" is the id of the object it refers to
1375                         if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1376                                 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1377                                 if (!empty($object_id)) {
1378                                         $object_data['reply-to-id'] = $object_id;
1379                                 }
1380                         }
1381                 } else {
1382                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1383                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1384                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1385                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1386                                 $object_data['reply-to-id'] = $replyToId;
1387                         }
1388                 }
1389
1390                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1391                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1392
1393                 if (empty($object_data['updated'])) {
1394                         $object_data['updated'] = $object_data['published'];
1395                 }
1396
1397                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1398                         $object_data['published'] = $object_data['updated'];
1399                 }
1400
1401                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1402                 if (empty($actor)) {
1403                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1404                 }
1405
1406                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1407                 $location = JsonLD::fetchElement($location, 'location', '@value');
1408                 if ($location) {
1409                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1410                         // down to HTML and then finally format to plaintext.
1411                         $location = Markdown::convert($location);
1412                         $location = BBCode::toPlaintext($location);
1413                 }
1414
1415                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1416                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1417                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1418                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1419                 $object_data['actor'] = $object_data['author'] = $actor;
1420                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1421                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1422                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1423                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1424                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1425                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1426                 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1427                 $object_data = self::getSource($object, $object_data);
1428                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1429                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1430                 $object_data['location'] = $location;
1431                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1432                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1433                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1434                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1435                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1436                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1437                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1438                 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1439                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1440                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1441                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1442
1443                 // Special treatment for Hubzilla links
1444                 if (is_array($object_data['alternate-url'])) {
1445                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1446
1447                         if (!is_string($object_data['alternate-url'])) {
1448                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1449                         }
1450                 }
1451
1452                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1453                         $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1454                         $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1455                 }
1456
1457                 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1458                 $receivers = $reception_types = [];
1459                 foreach ($receiverdata as $key => $data) {
1460                         $receivers[$key] = $data['uid'];
1461                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1462                 }
1463
1464                 $object_data['receiver'] = $receivers;
1465                 $object_data['reception_type'] = $reception_types;
1466
1467                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1468                 unset($object_data['receiver'][-1]);
1469                 unset($object_data['reception_type'][-1]);
1470
1471                 // Common object data:
1472
1473                 // Unhandled
1474                 // @context, type, actor, signature, mediaType, duration, replies, icon
1475
1476                 // Also missing: (Defined in the standard, but currently unused)
1477                 // audience, preview, endTime, startTime, image
1478
1479                 // Data in Notes:
1480
1481                 // Unhandled
1482                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1483                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1484
1485                 // Data in video:
1486
1487                 // To-Do?
1488                 // category, licence, language, commentsEnabled
1489
1490                 // Unhandled
1491                 // views, waitTranscoding, state, support, subtitleLanguage
1492                 // likes, dislikes, shares, comments
1493
1494                 return $object_data;
1495         }
1496 }