]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Receiver.php
Avoid thread completion on activities
[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                 if (!empty($activity['thread-children-type'])) {
519                         $object_data['thread-children-type'] = $activity['thread-children-type'];
520                 }
521
522                 // Internal flag for posts that arrived via relay
523                 if (!empty($activity['from-relay'])) {
524                         $object_data['from-relay'] = $activity['from-relay'];
525                 }
526
527                 switch ($type) {
528                         case 'as:Create':
529                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
530                                         $item = ActivityPub\Processor::createItem($object_data);
531                                         ActivityPub\Processor::postItem($object_data, $item);
532                                 }
533                                 break;
534
535                         case 'as:Add':
536                                 if ($object_data['object_type'] == 'as:tag') {
537                                         ActivityPub\Processor::addTag($object_data);
538                                 }
539                                 break;
540
541                         case 'as:Announce':
542                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
543                                         $object_data['thread-completion'] = Contact::getIdForURL($actor);
544
545                                         $item = ActivityPub\Processor::createItem($object_data);
546                                         if (empty($item)) {
547                                                 return;
548                                         }
549
550                                         $item['post-reason'] = Item::PR_ANNOUNCEMENT;
551                                         ActivityPub\Processor::postItem($object_data, $item);
552
553                                         $announce_object_data = self::processObject($activity);
554                                         $announce_object_data['name'] = $type;
555                                         $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
556                                         $announce_object_data['object_id'] = $object_data['object_id'];
557                                         $announce_object_data['object_type'] = $object_data['object_type'];
558                                         $announce_object_data['push'] = $push;
559
560                                         if (!empty($body)) {
561                                                 $announce_object_data['raw'] = $body;
562                                         }
563
564                                         ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
565                                 }
566                                 break;
567
568                         case 'as:Like':
569                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
570                                         ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
571                                 }
572                                 break;
573
574                         case 'as:Dislike':
575                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
576                                         ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
577                                 }
578                                 break;
579
580                         case 'as:TentativeAccept':
581                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
582                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
583                                 }
584                                 break;
585
586                         case 'as:Update':
587                                 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
588                                         ActivityPub\Processor::updateItem($object_data);
589                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
590                                         ActivityPub\Processor::updatePerson($object_data);
591                                 }
592                                 break;
593
594                         case 'as:Delete':
595                                 if ($object_data['object_type'] == 'as:Tombstone') {
596                                         ActivityPub\Processor::deleteItem($object_data);
597                                 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
598                                         ActivityPub\Processor::deletePerson($object_data);
599                                 }
600                                 break;
601
602                         case 'as:Follow':
603                                 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
604                                         ActivityPub\Processor::followUser($object_data);
605                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
606                                         $object_data['reply-to-id'] = $object_data['object_id'];
607                                         ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
608                                 }
609                                 break;
610
611                         case 'as:Accept':
612                                 if ($object_data['object_type'] == 'as:Follow') {
613                                         ActivityPub\Processor::acceptFollowUser($object_data);
614                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
615                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
616                                 }
617                                 break;
618
619                         case 'as:Reject':
620                                 if ($object_data['object_type'] == 'as:Follow') {
621                                         ActivityPub\Processor::rejectFollowUser($object_data);
622                                 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
623                                         ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
624                                 }
625                                 break;
626
627                         case 'as:Undo':
628                                 if (($object_data['object_type'] == 'as:Follow') &&
629                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
630                                         ActivityPub\Processor::undoFollowUser($object_data);
631                                 } elseif (($object_data['object_type'] == 'as:Accept') &&
632                                         in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
633                                         ActivityPub\Processor::rejectFollowUser($object_data);
634                                 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
635                                         in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
636                                         ActivityPub\Processor::undoActivity($object_data);
637                                 }
638                                 break;
639
640                         default:
641                                 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
642                                 break;
643                 }
644         }
645
646         /**
647          * Fetch the receiver list from an activity array
648          *
649          * @param array   $activity
650          * @param string  $actor
651          * @param array   $tags
652          * @param boolean $fetch_unlisted
653          *
654          * @return array with receivers (user id)
655          * @throws \Exception
656          */
657         private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
658         {
659                 $reply = $receivers = [];
660
661                 // When it is an answer, we inherite the receivers from the parent
662                 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
663                 if (!empty($replyto)) {
664                         $reply = [$replyto];
665
666                         // Fix possibly wrong item URI (could be an answer to a plink uri)
667                         $fixedReplyTo = Item::getURIByLink($replyto);
668                         if (!empty($fixedReplyTo)) {
669                                 $reply[] = $fixedReplyTo;
670                         }
671                 }
672
673                 // Fetch all posts that refer to the object id
674                 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
675                 if (!empty($object_id)) {
676                         $reply[] = $object_id;
677                 }
678
679                 if (!empty($reply)) {
680                         $parents = Post::select(['uid'], ['uri' => $reply]);
681                         while ($parent = Post::fetch($parents)) {
682                                 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
683                         }
684                         DBA::close($parents);
685                 }
686
687                 if (!empty($actor)) {
688                         $profile   = APContact::getByURL($actor);
689                         $followers = $profile['followers'] ?? '';
690                         $is_forum  = ($actor['type'] ?? '') == 'Group';
691                         Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
692                 } else {
693                         Logger::info('Empty actor', ['activity' => $activity]);
694                         $followers = '';
695                         $is_forum  = false;
696                 }
697
698                 // We have to prevent false follower assumptions upon thread completions
699                 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
700
701                 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
702                         $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
703                         if (empty($receiver_list)) {
704                                 continue;
705                         }
706
707                         foreach ($receiver_list as $receiver) {
708                                 if ($receiver == self::PUBLIC_COLLECTION) {
709                                         $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
710                                 }
711
712                                 // Add receiver "-1" for unlisted posts
713                                 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
714                                         $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
715                                 }
716
717                                 // Fetch the receivers for the public and the followers collection
718                                 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
719                                         $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
720                                         continue;
721                                 }
722
723                                 // Fetching all directly addressed receivers
724                                 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
725                                 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
726                                 if (!DBA::isResult($contact)) {
727                                         continue;
728                                 }
729
730                                 // Check if the potential receiver is following the actor
731                                 // Exception: The receiver is targetted via "to" or this is a comment
732                                 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
733                                         $networks = Protocol::FEDERATED;
734                                         $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
735                                                 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
736
737                                         // Forum posts are only accepted from forum contacts
738                                         if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
739                                                 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
740                                         }
741
742                                         if (!DBA::exists('contact', $condition)) {
743                                                 continue;
744                                         }
745                                 }
746
747                                 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
748                                 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
749                                         switch ($element) {
750                                                 case 'as:to':
751                                                         $type = self::TARGET_TO;
752                                                         break;
753                                                 case 'as:cc':
754                                                         $type = self::TARGET_CC;
755                                                         break;
756                                                 case 'as:bto':
757                                                         $type = self::TARGET_BTO;
758                                                         break;
759                                                 case 'as:bcc':
760                                                         $type = self::TARGET_BCC;
761                                                         break;
762                                         }
763
764                                         $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
765                                 }
766                         }
767                 }
768
769                 self::switchContacts($receivers, $actor);
770
771                 return $receivers;
772         }
773
774         /**
775          * Fetch the receiver list of a given actor
776          *
777          * @param string  $actor
778          * @param array   $tags
779          * @param array   $receivers
780          * @param integer $target_type
781          *
782          * @return array with receivers (user id)
783          * @throws \Exception
784          */
785         private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
786         {
787                 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
788                         'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
789
790                 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
791                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
792                 while ($contact = DBA::fetch($contacts)) {
793                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
794                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
795                         }
796                 }
797                 DBA::close($contacts);
798
799                 // The queries are split because of performance issues
800                 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
801                 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
802                 while ($contact = DBA::fetch($contacts)) {
803                         if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
804                                 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
805                         }
806                 }
807                 DBA::close($contacts);
808                 return $receivers;
809         }
810
811         /**
812          * Tests if the contact is a valid receiver for this actor
813          *
814          * @param array  $contact
815          * @param string $actor
816          * @param array  $tags
817          *
818          * @return bool with receivers (user id)
819          * @throws \Exception
820          */
821         private static function isValidReceiverForActor($contact, $tags)
822         {
823                 // Are we following the contact? Then this is a valid receiver
824                 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
825                         return true;
826                 }
827
828                 // When the possible receiver isn't a community, then it is no valid receiver
829                 $owner = User::getOwnerDataById($contact['uid']);
830                 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
831                         return false;
832                 }
833
834                 // Is the community account tagged?
835                 foreach ($tags as $tag) {
836                         if ($tag['type'] != 'Mention') {
837                                 continue;
838                         }
839
840                         if (Strings::compareLink($tag['href'], $owner['url'])) {
841                                 return true;
842                         }
843                 }
844
845                 return false;
846         }
847
848         /**
849          * Switches existing contacts to ActivityPub
850          *
851          * @param integer $cid Contact ID
852          * @param integer $uid User ID
853          * @param string  $url Profile URL
854          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
855          * @throws \ImagickException
856          */
857         public static function switchContact($cid, $uid, $url)
858         {
859                 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
860                         Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
861                         return;
862                 }
863
864                 if (Contact::updateFromProbe($cid)) {
865                         Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
866                 }
867
868                 // Send a new follow request to be sure that the connection still exists
869                 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
870                         Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
871                         ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
872                 }
873         }
874
875         /**
876          *
877          *
878          * @param $receivers
879          * @param $actor
880          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
881          * @throws \ImagickException
882          */
883         private static function switchContacts($receivers, $actor)
884         {
885                 if (empty($actor)) {
886                         return;
887                 }
888
889                 foreach ($receivers as $receiver) {
890                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
891                         if (DBA::isResult($contact)) {
892                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
893                         }
894
895                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
896                         if (DBA::isResult($contact)) {
897                                 self::switchContact($contact['id'], $receiver['uid'], $actor);
898                         }
899                 }
900         }
901
902         /**
903          *
904          *
905          * @param       $object_data
906          * @param array $activity
907          *
908          * @return mixed
909          */
910         private static function addActivityFields($object_data, $activity)
911         {
912                 if (!empty($activity['published']) && empty($object_data['published'])) {
913                         $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
914                 }
915
916                 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
917                         $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
918                 }
919
920                 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
921                 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
922
923                 if (!empty($object_data['object_id'])) {
924                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
925                         $objectId = Item::getURIByLink($object_data['object_id']);
926                         if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
927                                 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
928                                 $object_data['object_id'] = $objectId;
929                         }
930                 }
931
932                 return $object_data;
933         }
934
935         /**
936          * Fetches the object data from external ressources if needed
937          *
938          * @param string  $object_id    Object ID of the the provided object
939          * @param array   $object       The provided object array
940          * @param boolean $trust_source Do we trust the provided object?
941          * @param integer $uid          User ID for the signature that we use to fetch data
942          *
943          * @return array|false with trusted and valid object data
944          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
945          * @throws \ImagickException
946          */
947         private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
948         {
949                 // By fetching the type we check if the object is complete.
950                 $type = JsonLD::fetchElement($object, '@type');
951
952                 if (!$trust_source || empty($type)) {
953                         $data = ActivityPub::fetchContent($object_id, $uid);
954                         if (!empty($data)) {
955                                 $object = JsonLD::compact($data);
956                                 Logger::info('Fetched content for ' . $object_id);
957                         } else {
958                                 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
959
960                                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
961                                 if (!DBA::isResult($item)) {
962                                         Logger::info('Object with url ' . $object_id . ' was not found locally.');
963                                         return false;
964                                 }
965                                 Logger::info('Using already stored item for url ' . $object_id);
966                                 $data = ActivityPub\Transmitter::createNote($item);
967                                 $object = JsonLD::compact($data);
968                         }
969
970                         $id = JsonLD::fetchElement($object, '@id');
971                         if (empty($id)) {
972                                 Logger::info('Empty id');
973                                 return false;
974                         }
975
976                         if ($id != $object_id) {
977                                 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
978                                 return false;
979                         }
980                 } else {
981                         Logger::info('Using original object for url ' . $object_id);
982                 }
983
984                 $type = JsonLD::fetchElement($object, '@type');
985                 if (empty($type)) {
986                         Logger::info('Empty type');
987                         return false;
988                 }
989
990                 // Lemmy is resharing "create" activities instead of content
991                 // We fetch the content from the activity.
992                 if (in_array($type, ['as:Create'])) {
993                         $object = $object['as:object'];
994                         $type = JsonLD::fetchElement($object, '@type');
995                         if (empty($type)) {
996                                 Logger::info('Empty type');
997                                 return false;
998                         }
999                         $object_data = self::processObject($object);
1000                 }
1001
1002                 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1003                 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1004                         $object_data = self::processObject($object);
1005
1006                         if (!empty($data)) {
1007                                 $object_data['raw'] = json_encode($data);
1008                         }
1009                         return $object_data;
1010                 }
1011
1012                 if ($type == 'as:Announce') {
1013                         $object_id = JsonLD::fetchElement($object, 'object', '@id');
1014                         if (empty($object_id) || !is_string($object_id)) {
1015                                 return false;
1016                         }
1017                         return self::fetchObject($object_id, [], false, $uid);
1018                 }
1019
1020                 Logger::info('Unhandled object type: ' . $type);
1021                 return false;
1022         }
1023
1024         /**
1025          * Converts the language element (Used by Peertube)
1026          *
1027          * @param array $languages
1028          * @return array Languages
1029          */
1030         public static function processLanguages(array $languages)
1031         {
1032                 if (empty($languages)) {
1033                         return [];
1034                 }
1035
1036                 $language_list = [];
1037
1038                 foreach ($languages as $language) {
1039                         if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1040                                 $language_list[$language['_:identifier']] = $language['as:name'];
1041                         }
1042                 }
1043                 return $language_list;
1044         }
1045
1046         /**
1047          * Convert tags from JSON-LD format into a simplified format
1048          *
1049          * @param array $tags Tags in JSON-LD format
1050          *
1051          * @return array with tags in a simplified format
1052          */
1053         public static function processTags(array $tags)
1054         {
1055                 $taglist = [];
1056
1057                 foreach ($tags as $tag) {
1058                         if (empty($tag)) {
1059                                 continue;
1060                         }
1061
1062                         $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1063                                 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1064                                 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1065
1066                         if (empty($element['type'])) {
1067                                 continue;
1068                         }
1069
1070                         if (empty($element['href'])) {
1071                                 $element['href'] = $element['name'];
1072                         }
1073
1074                         $taglist[] = $element;
1075                 }
1076                 return $taglist;
1077         }
1078
1079         /**
1080          * Convert emojis from JSON-LD format into a simplified format
1081          *
1082          * @param array $emojis
1083          * @return array with emojis in a simplified format
1084          */
1085         private static function processEmojis(array $emojis)
1086         {
1087                 $emojilist = [];
1088
1089                 foreach ($emojis as $emoji) {
1090                         if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1091                                 continue;
1092                         }
1093
1094                         $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1095                         $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1096                                 'href' => $url];
1097
1098                         $emojilist[] = $element;
1099                 }
1100
1101                 return $emojilist;
1102         }
1103
1104         /**
1105          * Convert attachments from JSON-LD format into a simplified format
1106          *
1107          * @param array $attachments Attachments in JSON-LD format
1108          *
1109          * @return array Attachments in a simplified format
1110          */
1111         private static function processAttachments(array $attachments)
1112         {
1113                 $attachlist = [];
1114
1115                 // Removes empty values
1116                 $attachments = array_filter($attachments);
1117
1118                 foreach ($attachments as $attachment) {
1119                         switch (JsonLD::fetchElement($attachment, '@type')) {
1120                                 case 'as:Page':
1121                                         $pageUrl = null;
1122                                         $pageImage = null;
1123
1124                                         $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1125                                         foreach ($urls as $url) {
1126                                                 // Single scalar URL case
1127                                                 if (is_string($url)) {
1128                                                         $pageUrl = $url;
1129                                                         continue;
1130                                                 }
1131
1132                                                 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1133                                                 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1134                                                 if (Strings::startsWith($mediaType, 'image')) {
1135                                                         $pageImage = $href;
1136                                                 } else {
1137                                                         $pageUrl = $href;
1138                                                 }
1139                                         }
1140
1141                                         $attachlist[] = [
1142                                                 'type'  => 'link',
1143                                                 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1144                                                 'desc'  => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1145                                                 'url'   => $pageUrl,
1146                                                 'image' => $pageImage,
1147                                         ];
1148                                         break;
1149                                 case 'as:Image':
1150                                         $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1151                                         $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1152                                         $imagePreviewUrl = null;
1153                                         // Multiple URLs?
1154                                         if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1155                                                 $imageVariants = [];
1156                                                 $previewVariants = [];
1157                                                 foreach ($urls as $url) {
1158                                                         // Scalar URL, no discrimination possible
1159                                                         if (is_string($url)) {
1160                                                                 $imageFullUrl = $url;
1161                                                                 continue;
1162                                                         }
1163
1164                                                         // Not sure what to do with a different Link media type than the base Image, we skip
1165                                                         if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1166                                                                 continue;
1167                                                         }
1168
1169                                                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1170
1171                                                         // Default URL choice if no discriminating width is provided
1172                                                         $imageFullUrl = $href ?? $imageFullUrl;
1173
1174                                                         $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1175
1176                                                         if ($href && $width) {
1177                                                                 $imageVariants[$width] = $href;
1178                                                                 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1179                                                                 $previewVariants[abs(632 - $width)] = $href;
1180                                                         }
1181                                                 }
1182
1183                                                 if ($imageVariants) {
1184                                                         // Taking the maximum size image
1185                                                         ksort($imageVariants);
1186                                                         $imageFullUrl = array_pop($imageVariants);
1187
1188                                                         // Taking the minimum number distance to the target distance
1189                                                         ksort($previewVariants);
1190                                                         $imagePreviewUrl = array_shift($previewVariants);
1191                                                 }
1192
1193                                                 unset($imageVariants);
1194                                                 unset($previewVariants);
1195                                         }
1196
1197                                         $attachlist[] = [
1198                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1199                                                 'mediaType' => $mediaType,
1200                                                 'name'  => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1201                                                 'url'   => $imageFullUrl,
1202                                                 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1203                                         ];
1204                                         break;
1205                                 default:
1206                                         $attachlist[] = [
1207                                                 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1208                                                 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1209                                                 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1210                                                 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1211                                                 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1212                                                 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1213                                                 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1214                                         ];
1215                         }
1216                 }
1217
1218                 return $attachlist;
1219         }
1220
1221         /**
1222          * Fetch the original source or content with the "language" Markdown or HTML
1223          *
1224          * @param array $object
1225          * @param array $object_data
1226          *
1227          * @return array
1228          * @throws \Exception
1229          */
1230         private static function getSource($object, $object_data)
1231         {
1232                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1233                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1234                 if (!empty($object_data['source'])) {
1235                         return $object_data;
1236                 }
1237
1238                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1239                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1240                 if (!empty($object_data['source'])) {
1241                         $object_data['source'] = Markdown::toBBCode($object_data['source']);
1242                         return $object_data;
1243                 }
1244
1245                 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1246                 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1247                 if (!empty($object_data['source'])) {
1248                         $object_data['source'] = HTML::toBBCode($object_data['source']);
1249                         return $object_data;
1250                 }
1251
1252                 return $object_data;
1253         }
1254
1255         /**
1256          * Extracts a potential alternate URL from a list of additional URL elements
1257          *
1258          * @param array $urls
1259          * @return string
1260          */
1261         private static function extractAlternateUrl(array $urls): string
1262         {
1263                 $alternateUrl = '';
1264                 foreach ($urls as $key => $url) {
1265                         // Not a list but a single URL element
1266                         if (!is_numeric($key)) {
1267                                 continue;
1268                         }
1269
1270                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1271                                 continue;
1272                         }
1273
1274                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1275                         if (empty($href)) {
1276                                 continue;
1277                         }
1278
1279                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1280                         if (empty($mediatype)) {
1281                                 continue;
1282                         }
1283
1284                         if ($mediatype == 'text/html') {
1285                                 $alternateUrl = $href;
1286                         }
1287                 }
1288
1289                 return $alternateUrl;
1290         }
1291
1292         /**
1293          * Check if the "as:url" element is an array with multiple links
1294          * This is the case with audio and video posts.
1295          * Then the links are added as attachments
1296          *
1297          * @param array $urls The object URL list
1298          * @return array an array of attachments
1299          */
1300         private static function processAttachmentUrls(array $urls): array
1301         {
1302                 $attachments = [];
1303                 foreach ($urls as $key => $url) {
1304                         // Not a list but a single URL element
1305                         if (!is_numeric($key)) {
1306                                 continue;
1307                         }
1308
1309                         if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1310                                 continue;
1311                         }
1312
1313                         $href = JsonLD::fetchElement($url, 'as:href', '@id');
1314                         if (empty($href)) {
1315                                 continue;
1316                         }
1317
1318                         $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1319                         if (empty($mediatype)) {
1320                                 continue;
1321                         }
1322
1323                         $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1324
1325                         if ($filetype == 'audio') {
1326                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1327                         } elseif ($filetype == 'video') {
1328                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1329                                 // PeerTube audio-only track
1330                                 if ($height === 0) {
1331                                         continue;
1332                                 }
1333
1334                                 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1335                                 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1336                         } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1337                                 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1338
1339                                 // For Torrent links we always store the highest resolution
1340                                 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1341                                         continue;
1342                                 }
1343
1344                                 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1345                         } elseif ($mediatype == 'application/x-mpegURL') {
1346                                 // PeerTube exception, actual video link is in the tags of this URL element
1347                                 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1348                         }
1349                 }
1350
1351                 return array_values($attachments);
1352         }
1353
1354         /**
1355          * Fetches data from the object part of an activity
1356          *
1357          * @param array $object
1358          *
1359          * @return array
1360          * @throws \Exception
1361          */
1362         private static function processObject($object)
1363         {
1364                 if (!JsonLD::fetchElement($object, '@id')) {
1365                         return false;
1366                 }
1367
1368                 $object_data = [];
1369                 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1370                 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1371                 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1372
1373                 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1374                 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1375                         $object_data['reply-to-id'] = $object_data['id'];
1376
1377                         // On activities the "reply to" is the id of the object it refers to
1378                         if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1379                                 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1380                                 if (!empty($object_id)) {
1381                                         $object_data['reply-to-id'] = $object_id;
1382                                 }
1383                         }
1384                 } else {
1385                         // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1386                         $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1387                         if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1388                                 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1389                                 $object_data['reply-to-id'] = $replyToId;
1390                         }
1391                 }
1392
1393                 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1394                 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1395
1396                 if (empty($object_data['updated'])) {
1397                         $object_data['updated'] = $object_data['published'];
1398                 }
1399
1400                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1401                         $object_data['published'] = $object_data['updated'];
1402                 }
1403
1404                 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1405                 if (empty($actor)) {
1406                         $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1407                 }
1408
1409                 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1410                 $location = JsonLD::fetchElement($location, 'location', '@value');
1411                 if ($location) {
1412                         // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1413                         // down to HTML and then finally format to plaintext.
1414                         $location = Markdown::convert($location);
1415                         $location = BBCode::toPlaintext($location);
1416                 }
1417
1418                 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1419                 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1420                 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1421                 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1422                 $object_data['actor'] = $object_data['author'] = $actor;
1423                 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1424                 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1425                 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1426                 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1427                 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1428                 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1429                 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1430                 $object_data = self::getSource($object, $object_data);
1431                 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1432                 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1433                 $object_data['location'] = $location;
1434                 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1435                 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1436                 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1437                 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1438                 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1439                 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1440                 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1441                 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1442                 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1443                 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1444                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1445
1446                 // Special treatment for Hubzilla links
1447                 if (is_array($object_data['alternate-url'])) {
1448                         $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1449
1450                         if (!is_string($object_data['alternate-url'])) {
1451                                 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1452                         }
1453                 }
1454
1455                 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1456                         $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1457                         $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1458                 }
1459
1460                 // For page types we expect that the alternate url posts to some page.
1461                 // So we add this to the attachments if it differs from the id.
1462                 // Currently only Lemmy is using the page type.
1463                 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1464                         $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1465                         $object_data['alternate-url'] = null;
1466                 }
1467
1468                 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1469                 $receivers = $reception_types = [];
1470                 foreach ($receiverdata as $key => $data) {
1471                         $receivers[$key] = $data['uid'];
1472                         $reception_types[$data['uid']] = $data['type'] ?? 0;
1473                 }
1474
1475                 $object_data['receiver'] = $receivers;
1476                 $object_data['reception_type'] = $reception_types;
1477
1478                 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1479                 unset($object_data['receiver'][-1]);
1480                 unset($object_data['reception_type'][-1]);
1481
1482                 // Common object data:
1483
1484                 // Unhandled
1485                 // @context, type, actor, signature, mediaType, duration, replies, icon
1486
1487                 // Also missing: (Defined in the standard, but currently unused)
1488                 // audience, preview, endTime, startTime, image
1489
1490                 // Data in Notes:
1491
1492                 // Unhandled
1493                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1494                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1495
1496                 // Data in video:
1497
1498                 // To-Do?
1499                 // category, licence, language, commentsEnabled
1500
1501                 // Unhandled
1502                 // views, waitTranscoding, state, support, subtitleLanguage
1503                 // likes, dislikes, shares, comments
1504
1505                 return $object_data;
1506         }
1507 }