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