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