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